Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django’s command-line utility | manage.py: command not found
I'm new to Django and trying to use manage.py instead of django-admin command as Django's documentation mentioned (https://docs.djangoproject.com/en/3.1/ref/django-admin/) so from what I learned, I can use these interchangeably. $ django-admin <command> [options] $ manage.py <command> [options] $ python -m django <command> [options] So my problem is when I use manage.py , the terminal says: manage.py: command not found Where is the problem? -
Image is not updating in Django
Please help me. I am trying to update the profile in which username and email are updated but the image dose not. My code is.... profile.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <br> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> </div> {% endblock content%} -
Django tag on template
My code: {% if request.user.is_staff %} {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Create A Post </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Post </button> </div> </form> </div> {% endblock content %} {% else %} <head> <meta http-equiv="refresh" content="5; url=/" /> </head> <body> <h1>Restricted Access To Staff!</h1> <p>You will be redirected to the home page in 5 seconds</p> </body> {% endif %} The Error: I can't figure out why it is not working, could it be something to do with the {% if request.user.is_staff %} bit? -
Change "python manage.py" to "./manage.py"
I want to short python manage.py to ./manage.py. Maybe simple question but could not find an answer for this (maybe googled wrongly). I saw step by step method in one of the answers for questions about django but I did not memorize that. Tried to search answers to questions on stackoverflow that I have been entered but no result. Any help would be appreciated. -
How to check witch user is logged in with django?
Hi there I am currently working on a website, and I wanted to know how do I check witch user is logged in. Just to clarify I am using the django build in models from django.contrib.auth.models import User to do my login, logout etc. What I don't know how to do is check witch user is logged in, I know the method if user.is_authenticated: # Other code goes here But this method only checks weather the user is logged in not witch user is logged in? can anyone tell me the solution to this problem, thank you in advance. -
Displaying / Testing outputs are correct. Sanity Check
I am still learning Django and slowly improving but I have a few questions, I have my whole model below: from django.db import models from datetime import datetime, timedelta # Create your models here. year_choice = [ ('year1','1-Year'), ('year3','3-Year') ] weeksinyear = 52 hours = 6.5 current_year = datetime.year class AdminData(models.Model): year1 = models.IntegerField() year3 = models.IntegerField() @property def day_rate_year1(self): return self.year1 / weeksinyear / hours class Price(models.Model): name = models.CharField(max_length=100) contract = models.CharField(max_length=5, choices=year_choice) start_date = models.DateField(default=datetime.now) end_date = models.DateField(default=datetime(2021,3,31)) def __str__(self): return self.name The main concern for me at the moment is trying to understand if my function def day_rate_year1(self): is working correctly, if someone could point me in the right direction to understand either how I display this as a string value in a template or test in the shell to see if the value pulls through as the values for year1 and year3 can change based on user input. I am trying to work out the day rate so I can then use the start and end dates and work out the number of days between the two to calculate a price which is then displayed to the user which can again change depending on the … -
TypeError and NoReverseMatch in django
When i go to /projects i get NoReverseMatch at /projects/ Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. when i go to /projects/some number i get TypeError at /projects/1/ 'Project' object is not iterable path main migrations templates detail.html home.html proceed.html project.html __init_.py admin.py apps.py models.py tests.py views.py portfolio __init_.py asgi.py settings.py urls.py wsgi.py db.sqlite3 manage.py views.py from django.shortcuts import render, get_object_or_404 from .models import Project # Create your views here. def home(request): return render(request, "home/home.html") def project(request): projects = Project.objects.all() return render(request, "home/project.html", {'projects':projects }) def detail(request, project_id): oof = get_object_or_404(Project, pk=project_id) return render(request, 'home/detail.html', {'projectss': oof}) detail.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css"> <link rel="stylesheet" href="https://static.pingendo.com/bootstrap/bootstrap-4.3.1.css"> </head> <body > <div class="py-5" style=" background-image: linear-gradient(to bottom, rgb(0, 0, 0), rgb(0, 0, 0)); background-position: center center; background-size: 100%; background-repeat: repeat;"> <div class="container"> <div class="row"> <div class="text-center mx-auto col-md-12"> <h1 class="text-light">Proceed to external site</h1> </div> </div> </div> </div> <div class="py-5 text-center" style=" background-image: linear-gradient(to bottom, rgb(0, 0, 0), rgb(0, 0, 0)); background-position: top left; background-size: 100%; background-repeat: repeat;"> <div class="container"> <div class="row"> {% for project in projectss %} <div class="mx-auto col-lg-5 col-md-7 col-10"> <h1 class="text-white mb-5">{project.title}</h1> … -
How do I use POST request and filter() for field lookup and return a dataset through an html page?
I want to get the values of attributes 'skill_required' and 'desired_level' from a user, filter the DB according to these values and send the matching rows of data through the html page 'emptracker.html' Problem is, I can't figure out how to send this data through the html template emptracker. The code for the view page is below: def emptracker(request): if request.method == 'POST': skill_required = request.POST['skill_required'], desired_level = request.POST['desired_level'] from app8.models import empskillmapping orgdata = empskillmapping.objects.filter(skill_required = skill_required).filter(desired_level = desired_level) **return render(request, 'emptracker.html',{'data': orgdata})** I encounter an error here saying that orgdata is out of scope, I just can't figure out how to render this data. emphasized text class empskillmapping(models.Model): skill_required = models.CharField(max_length=20) desired_level = models.ForeignKey(level,on_delete=models.CASCADE,default="", editable= True) department_id = models.ForeignKey(department,on_delete=models.CASCADE,default="", editable= True) This is the model I want to search. -
Django internationalization does not work
Hello guys it's me again and for this question i scruwed so bad. I've started to do django's internationalization and it doesn't work i couldn't find anything about my problem here is my codes: settings.py: MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGE_CODE = 'tr' TIME_ZONE = 'Europe/Istanbul' USE_I18N = True USE_L10N = True USE_TZ = True LOCAL_PATHS = { os.path.join(BASE_DIR, 'locale') } urls.py from django.contrib import admin from django.urls import path from django.urls.conf import include from product import views from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( path('', views.index, name="index"), ... path('about/', views.about,name="about-en"), ... prefix_default_language = False, )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def about(request): abouts = Hakkimizda.objects.first() return render(request,"about.html",{"abouts":abouts}) about.html (i just did this for see how it work but it didn't work) <h2> {% translate "denseme" %}</h2> django.po ... #: .\templates\about.html:5 .\templates\about.html:11 msgid "denseme" msgstr "abc" -
Django Import CSV KeyError
I'm getting this error. I can't figure out why. This has worked fine before. I don't recall making any changes that would cause this to happen. When I try to upload a .csv to my database: KeyError at /upload/ .....\views.py line 112, in post objs = [ <------ line 112 .....\views.py line 114, in listcomp description=row['description'], <-------- line 114 Here is my view class UploadView(View): def get(self, request): template_name = 'crmapp/upload.html' return render(request, template_name) def post(self, request): user = request.user # get the current login user details paramFile = io.TextIOWrapper(request.FILES['uploadfile'].file) portfolio1 = csv.DictReader(paramFile) list_of_dict = list(portfolio1) objs = [ Product( description=row['description'], costprice=row['costprice'], retailprice=row['retailprice'], barcode=row['barcode'], ) for row in list_of_dict ] try: msg = Product.objects.bulk_create(objs) returnmsg = {"status_code": 200} print('imported successfully') except Exception as e: print('Error While Importing Data: ', e) returnmsg = {"status_code": 500} return JsonResponse(returnmsg) models.py class Product(models.Model): description = models.CharField(max_length=30) costprice = models.FloatField(null=True, max_length=99, blank=True) retailprice = models.FloatField(null=True, max_length=99, blank=True) barcode = models.CharField(null=True, max_length=99, unique=True, blank=True) image = DefaultStaticImageField(null=True, blank=True,default='images/item_gC0XXrx.png') supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=False, blank=False) and this is the template upload.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="uploadfile"> <hr> <br> <button type="submit" class='btn btn-success'>Upload</button> </form> -
django rest frame work with react using webpack
i successfully connected DRF to react after seeing the posting. https://www.valentinog.com/blog/drf/ but real-time screen update is not possible when the server is run in development mode by typing the phrase. "webpack --mode development ./src/index.js --output-path ./static/frontend/main.js" -
How can I record form responses in Django
I'm attempting to record an answer to a basic y/n question and send it from HTML to a Django view. This is my html code: form.html <form method="POST"> {% csrf_token %} <div id="drinks"> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <label> <div class="mySlides" style="display: block;"> <img src="{{ prof_pic }}" alt="image alt text" width="100" height="100"/> <div> <select name="dance_or_no" required> <option value = "" disabled="disabled" selected="selected">Ques.</option> <option value = "yes">Yes :)</option> <option value = "no">No :(</option> </select> </div> </div> </label> </div> <input type="submit" value="Submit" class="drink-it"> </form> Once the user submits this form it gets sent to auth in views.py def auth(request): if request.method == 'POST': dance_or_no = request.POST.get('dance_or_no', False) request.session['dance_or_no'] = dance_or_no print('authenticated!!') return redirect(client.generate_auth_url()) def callback(request): dance_or_no = request.session.get('dance_or_no) This route authenticates the user, which is mandatory for the website to work. So the form answers are also directed here. I am attempting to record the answer and create a session cookie to send to another view. But this dance_or_no value always gets a None value. I have done this in flask. And it worked this way, but now when I'm migrating to Django I can't seem to understand the way one can save an option form and send it from one … -
Django/PostgreSQL Project unable to run due to 'missing' libssl file
I'm trying to set up a local version of a web project made with Django and PostgreSQL. However, when I'm trying to 'run' it (makemigrations, runserver..) I get the following errors: ImportError: dlopen(/Users/my_username/Library/Python/3.8/lib/python/site-packages/psycopg2/_psycopg.cpython-38-darwin.so, 2): Library not loaded: libssl.1.1.dylib Referenced from: /Users/my_username/Library/Python/3.8/lib/python/site-packages/psycopg2/_psycopg.cpython-38-darwin.so Reason: image not found During handling of the above exception, another exception occurred: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/quentinbackaert/Library/Python/3.8/lib/python/site-packages/psycopg2/_psycopg.cpython-38-darwin.so, 2): Library not loaded: libssl.1.1.dylib Referenced from: /Users/quentinbackaert/Library/Python/3.8/lib/python/site-packages/psycopg2/_psycopg.cpython-38-darwin.so Reason: image not found I haven't included the full Traceback for readability reasons, but if needed I'll include it. Openssl, PostgreSQL and the psycopg2 module seems to be installed properly. I did the following command: ls /usr/lib | grep "ssl" libboringssl.dylib libssl.0.9.7.dylib libssl.0.9.8.dylib libssl.35.dylib libssl.43.dylib libssl.44.dylib libssl.46.dylib libssl.dylib So i think the file in the proper version (1.1) is missing or not in the right place. I checked several other posts with the same issues, but wasn't able to solve the problem. I'm pretty new to this so I'm a bit confused on what I should do. I'm on MacOS Catalina. -
Exception while using threading library in Django
I have been experiencing some issues while using basic threading in Django Here is my script from threading import Thread def run_threads(msg1, msg2): class Hello(Thread): def run(self): for i in range(500): print(msg1) class Hi(Thread): def run(self): for i in range(500): print(msg2) t1 = Hello() t2 = Hi() t1.start() t2.start() t1.join() t2.join() print("Here") But upon running, it is giving me following error somethingException in thread Exception in threading.excepthook:Exception ignored in thread started byException ignored in sys.unraisablehookis cookingException in thread Exception in threading.excepthook:E xception ignored in thread started byException ignored in sys.unraisablehookHere But if I run it in Python3 console without Django, it works alright. Any help would be highly appreciated Information on my system: Python: 3.8 Django: (3, 1, 4, 'final', 0) -
Django migrate AttributeError: 'str' object has no attribute '_meta'
After doing some extensive changes in the DB schema, I ran makemigrations. It created migrations successfully. But then migrate failed with: AttributeError: 'str' object has no attribute '_meta' This is the code that I changed. I split up the Many to Many model for Hardskills from one through table to 2 different through table for users and jobs. Initial class Hardskills(models.Model): user = models.ManyToManyField(User, related_name="user_hs",through="HardskillsProfile") job = models.ManyToManyField(Job, related_name="job_hs",through="HardskillsProfile") hardskills = models.CharField(max_length=100, db_index=True) def __str__(self): return self.hardskills class HardskillsProfile(models.Model): """Through Model for Many to Many relationship for user/jobs and hardskills""" user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user",null=True) job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name="job",null=True) hardskills = models.ForeignKey(Hardskills, on_delete=models.CASCADE) Final after changes from attributes.models import Category from django.contrib.auth.models import User from content.models import Job from django.db import models class Hardskills(models.Model): user = models.ManyToManyField(User, related_name="user_hs",through="UserHardskillsProfile") job = models.ManyToManyField(Job, related_name="job_hs",through="JobHardskillsProfile") hardskills = models.CharField(max_length=100, db_index=True) def __str__(self): return self.hardskills class UserHardskillsProfile(models.Model): """Through Model for Many to Many relationship for user and hardskills""" user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user",null=True) hardskills = models.ForeignKey(Hardskills, on_delete=models.CASCADE) class JobHardskillsProfile(models.Model): """Through Model for Many to Many relationship for user/jobs and hardskills""" job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name="job",null=True) hardskills = models.ForeignKey(Hardskills, on_delete=models.CASCADE) Error Logs Operations to perform: Synchronize unmigrated apps: messages, rest_framework, staticfiles Apply all migrations: accounts, … -
How can I get kwargs values in redirected view
I'm trying to send user to "payment view" after user register. here is what i try: ''' def dispatch(): ...... #user registration code ... #then i want to send email to redirected page new_user_email =form.cleaned_data.get('email') print("user registration complete") else: message = form.errors messages.error(request, message) print('form not verified '+ str(form.errors)) return redirect(reverse('account:payment'),kwargs = {'email': new_user_email}) ''' url: ''' path('payment/', views.PaymentView.as_view(), name = 'payment'), ''' and after go to payment view i want to get email in this view. ''' class PaymentView(TemplateView): ''' For Payment related information and proceed to get new subscription. ''' template_name = 'home/payment.html' def get_context_data(self,*args, **kwarg): context = super().get_context_data(*args, **kwarg) .... # here i need email # context['email'] = return context ''' how can i do it? -
Creating API for existing Django project
I have made a project using Django and haven't written any APIs for that yet. But, Now I want to write the APIs for the same (for maybe React or mobile app) and I'm wondering do I have to rewrite all the complex views to create the APIs. I'm new with this, what should be the approach to create APIs for the existing Django code? -
Does rest_framework.test library generate an external database?
The question pretty much sums itself up, when running tests Djangos testing framework generates an external database and then deletes it when tests are completed, my question is: Does DRFs testing framework do the same or does it run tests against existing database? -
filter multiple date rannge and use them precisely django
This is my models class AccountTransactions(models.Model): advertiser_id = models.ForeignKey('Advertisers', on_delete=models.CASCADE,null=True, db_column='advertiser_id', related_name='transactions') amount = models.DecimalField(max_digits=13, decimal_places=4, blank=True, null=True) description = models.CharField(max_length=100, blank=True, null=True) open_balance = models.DecimalField(max_digits=13, decimal_places=4) balance = models.DecimalField(max_digits=13, decimal_places=4) appnexus_charges = models.DecimalField(max_digits=13, decimal_places=4, blank=True, null=True) commision = models.DecimalField(max_digits=13, decimal_places=4, blank=True, null=True) transaction_date = models.DateTimeField() topup_transaction_id = models.CharField(max_length=100, blank=True, null=True) tnc_accepted_flag = models.IntegerField(blank=True, null=True) What i want to do is : 1)find balance for starting date of current month and ending date of current month 2)find balance for starting date of previous month and ending date of previous month I have written code for the same but there are two issues with the code: 1)Multiple times firing query i.e one for current month and one for other month. 2)I am filtering using start_date and end_date and then checking balance between the date range, but if there is no entry for that month in database it will output 0 but my api should output last transaction value in entry. My code: class AdvertiserAccountViewset(viewsets.ViewSet): """ Account transaction details of advertiser""" def retrieve(self, request, pk=None, format=None): start_date = request.query_params.get('start_date') end_date = request.query_params.get('end_date') res_data = {} res_data["advertiser_name"] = adv_name first_date_month = str(datetime.date.today())[:-2] + "01" today = datetime.date.today() first = today.replace(day=1) pre_first_date = str(first … -
How to overwrite Django app to Pythonanywhere?
After the second times deploying the Django app to Pythonanywhere, (I re-edited and overwritten in VS code and did git push) I got the following error. subprocess.CalledProcessError: Command'['/home/hogehoge/.virtualenvs/hogehoge.pythonanywhere.com/bin/pip','show','django']' returned non-zero exit status 1. The command is $ pa_autoconfigure_django.py https://github.com/[user_name]/[project_name].git --nuke The first deployment succeeded but the second one is not. I don't know the cause and how to overwrite it... -
Django Admin: Display unique field values and its count in the list_display
I have EmployeePoint Model to track the points of the employee. The object is saved when deal is successful. if obj.deal_status == 'Successful': point_obj = EmployeePoint(employee=lead.employee, created_at=obj.created_at) point_obj.save() Currently the list_display() displays all the objects. list_display of EmployeePoint Instead of displaying all the objects of EmployeePoint, I want something like list_display= ('employee','count') to display employee name and number of objects with that employee name created in current year. -
Error no such table: forms_complain in django
I have created a html file 'Complain' and its supposed to take input from user and store in in the database. My complain.html is <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>Hello People</h1> <form action="/complain/" method="post"> {% csrf_token %} <label for="name">Your Name</label> <input type="text" name="Std_name" placeholder="John Doe"><br><br> <label for="Std_id">Your Student ID</label> <input type="number" name="Std_id" placeholder="01"><br><br> <label for="Std_class">Your Class</label> <input type="text" name="Std_class" placeholder="Class 1"><br><br> <label for="email">Your Email</label> <input type="email" name="email" placeholder="abc@gmail.com"><br><br> <label for="desc">Your Complaint</label> <input type="text" name="desc"><br><br> <button type="submit">Submit</button> </form> </body> </html> and models.py is from django.db import models from django.forms import ModelForm from django.utils import timezone class Complain(models.Model): Std_no = models.AutoField(primary_key=True) Std_id = models.IntegerField(max_length=None) Std_class = models.TextField() name = models.CharField(max_length=40) email = models.CharField(max_length=40) desc = models.TextField() time = models.DateTimeField(auto_now_add=True) Views.py is from django.shortcuts import render from django.http import HttpResponse from django.db.models import Q from .models import Complaint, Complain def complain(request): if request.method=='POST': name = request.POST.get("name") Std_id = request.POST.get("Std_id") Std_class = request.POST.get("Std_class") email = request.POST.get("email") desc = request.POST.get("desc") instance = Complain(name=name, Std_id=Std_id, Std_class=Std_class, email=email, desc=desc) instance.save() return render(request,'forms/complain.html', { 'title' : 'Complain'}) I have run python manage.py makemigration python manage.py migrate python manage.py sqlmigrate forms and someone recommended on stack overflow to run python manage.py migrate --run-syncdb so I tried it … -
Filter query using headers in DRF
I have a use case where I need to show the data of the company the user belongs to. I don't want the url to show something like: 127.0.0.1:8000/api/document?company=somecompany rather I want to pass the company within the header and return the data related to the company. Is there any way to achieve this in Django REST Framework? Else, how can I avoid 127.0.0.1:8000/api/document?company=somecompany. -
Updating database when a user clicks a button (django)
I have been working on a project, in which I found, that we have to send a post request to another view(ex. update_item) when a button is clicked. And we use that same view to fetch the data to be added to database. Please explain the working on how this is done in django. -
RapidSMS Installation Error in Ubuntu 20.10
Please help my issue. I doing like this, but migrate step in error. #pip install rapidsms #pip install django #django-admin.py startproject --template=https://github.com/rapidsms/rapidsms-project-template/zipball/release-0.21.1 --extension=py,rst start_rsms1 #virtualenv start_rsms1-env #source start_rsms1-env/bin/activate #cd start_rsms1 #pip install -U -r requirements/base.txt #python manage.py migrate #python manage.py runserver ------------------Error class Message(models.Model): RuntimeError: class not set defining 'Message' as <class 'rapidsms.contrib.messagelog.models.Message'>. Was classcell propagated to type.new?