Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Docker/Postgresql - psycopg2 error
hope you can help me with my following issues. This is my first time using docker and docker-compose. I'm trying to "dockerize" my Django project running on Postgresql database and I'm having an issues with psycopg2 module. I'm using psycopg2-binary, as it's normaly the only one that works with my configuration. I've tried the standard psycopg2 package but it still doesn't work. So I will begin by showing you some of my files: relevant part of settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIRS = os.path.join(BASE_DIR, "templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', 'changeme') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] ALLOWED_HOSTS_ENV = os.environ.get('ALLOWED_HOSTS') if ALLOWED_HOSTS_ENV: ALLOWED_HOSTS.extend(ALLOWED_HOSTS_ENV.split(',')) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'core.apps.CoreConfig', 'django.contrib.staticfiles', 'jquery', 'ckeditor', 'ckeditor_uploader', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'littledreamgardens.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'core/templates/core/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'core.views.category_list', ], }, }, … -
Django templates: Calling super in case of multi-level extends
This is my current template structure: example_template_1.html example_template_2.html extends example_template_1.html example_template_3.html extends example_template_2.html How would I get content of a specific block from example_template_1.html in example_template_3.html? Basically, I need something that does {{ block.super.super }} in example_template_3.html to override the contents of a specific block in example_template_1.html. Is that possible? -
301 redirect router for Django project
I have a website building tool created in Django and I'd like to add easy user defined 301 redirects to it. Webflow has a very easy to understand tool for 301 redirects. You add a path (not just a slug) and then define where that path should lead the user. I'd like to do the same for the Django project I'm working on. I currently allow users to set a slug that redirects (/<slug:redirect_slug>/) and they can set to go to any URL. But I'd like them to be able to add, for example, the path for an old blog post ('/2018/04/12/my-favorite-thing/') What's the best URL conf to use in Django to safely accept any path the user wants? -
No module named error If I create and use batch file in Django project
I am trying to create batch file that will use for "Task Scheduler". It will update my database from csv file daily. Even py manage.py runscript delete_data is running in Django shell command, I faced following error after run batch file. File "*****\Desktop\argeportal\scripts\delete_data.py", line 4, in <module> from core.models import News ModuleNotFoundError: No module named 'core' What I am missing? How can I create it? My script py from core.models import News import csv def run(): with open(r"csvdata.csv") as f: reader = csv.reader(f, delimiter=';', quotechar='"') next(reader) # Advance past the header News.objects.all().delete() print(reader) for row in reader: print(row) c = News(id=row[0], title=row[1], body=row[2], content=row[3], addedDate=row[4], updateDate=row[5], newsImg=row[6]) c.save() My batch file @echo off "C:\Users\bense\AppData\Local\Programs\Python\Python38-32\python.exe" "C:\Users\bense\Desktop\argeportal\scripts\delete_data.py" cmd /k -
Birthdays employee Django Model
I have a model with employees data, name, photo, date of birth and etc. I'm trying to create a url that shows the birthdays of the employees where I can filter, if i click at one button, filter the birthdays of the day, another button, birthdays of the week and so on. I'm don't know where I can work with the date of birth to generate theses "category". I'm looking for ideas to implement these Thanks in advance -
How to pass on value to particular title in django
I have fetched the value from my table MarketingMaestro whose structure is given below Structure of MarketingMaestro class MarketingMaestro (models.Model): product_title = models.CharField(max_length=250) total_value = models.IntegerField() total_votes = models.IntegerField() I am able to fetch the value perfectly using for loop which gives the below output in the html So when you click on Invest button from one of the card, you will be able to invest some amount into that particular project. Popup looks like this So I am facing two issues here, I am not able to display the particular project name whos invest button is clicked, and after adding the amount and submitting it I am not getting any error but it is not getting saved in the database. I am not getting the idea how should I pass the project name to the ajax code. AJAX code $(document).on('submit', '#post-form',function(e){ // console.log("Amount="+$('input[name="amount"]').val()); e.preventDefault(); // getting the value entered amount = $('input[name="amount"]').val(); console.log("Amount entered by user="+amount); $.ajax({ type:'POST', url:'{% url "brand" %}', data:{ name: name, emailID: emailID, product_title: product_title, total_investment : total_investment, amount: amount, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' … -
How to Validate Against Current User in Django?
I have following model class User(AbstractBaseUser, PermissionsMixin): #: First and last name do not cover name patterns around the globe username = CharField(max_length=100,unique=True) email = models.EmailField(_('email address'), unique=True) full_name = TitleCharField(max_length=100) phone_number = PhoneNumberField() referred_by = models.ForeignKey('self', on_delete=models.CASCADE) is_member = models.BooleanField(default=False) is_active = models.BooleanField(default=False) Scenario is same user cannot be a user and referred by user. what I have done so far is def clean(self): if self == self.referred_by: raise DjangoValidationError({'referred_by': _('Same user cannot be referred by user')}) I don't feel I am doing right what shall I do? -
Return querysets
here is the code : def some_brand_mobiles(*brand_names): if not brand_names: return (Mobile.objects.all()) else: for brand in brand_names: return Mobile.objects.filter(brand__name=brand) the expected output for some_brand_mobiles('Apple', 'Huawei', 'Samsung') : <QuerySet [<Mobile: Apple iphone 8>, <Mobile: Apple iphone 10>, <Mobile: Apple iphone XIII>]> <QuerySet [<Mobile: Huawei P40>, <Mobile: Huawei P10 Pro>, <Mobile: Huawei P90 Pro>]> <QuerySet [<Mobile: Samsung A80>, <Mobile: Samsung A70>]> instead, it returns this only: <QuerySet [<Mobile: Apple iphone 8>, <Mobile: Apple iphone 10>, <Mobile: Apple iphone XIII>]> I know using a return inside of a loop will break the loop and exit the function even if the iteration is not over and I have two options either yielding or appending data to a list and then return the list but none of them work for me and I do not know how to do that and any help would be appreciated -
Serializing list of object in Django to nested json
I am new to Django/Python and was trying to work on project. I have to create an API with nested values like below { "rule": "ruleA" "criticality" : "High" "user": [ { "email" : "xyz@gmail.com" "username" : "xyz" }, { "email" : "abc@gmail.com" "username" : "abc" } ] } { "rule": "ruleB" "criticality" : "low" "user": [ { "email" : "pqr@gmail.com" "username" : "pqr" } ] } Below is my serializer.py class userSerializer(serializers.Serializer): email = serializers.CharField() username= serializers.CharField() class cloudScoreAnalysisSerializer(serializers.Serializer): rules = serializers.CharField() criticality = serializers.CharField() user = userSerializer(many=True,source='*') While running this code I'm getting attribute error: Got AttributeError when attempting to get a value for field `email` on serializer `userSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. It seems like the code is unable to find the email filed as it's inside the json array ([ { } ]) . Kindly help. -
How to split fields of model class between different views and templates to take inputs in different forms?
I have a class in my models.py with name 'Client', and it has different fields like (name, dob.. etc). I have a view for that called 'ClientCreateView' in views.py in which I am taking input in some fields of Client class (NOT all fields). And the template for this is called 'client_form.html'. Related files are given below: models.py: class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField(default = 0) views.py: class ClientCreateView(CreateView): model = Client fields = ['name', 'dob', 'CNIC', 'property_type', 'down_payment'] class AddInstallmentView(CreateView): model = Client fields = ['installment_month', 'installment_amount'] client_form.html {% extends "property_details/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"> Add New Client</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Add Client</button> </div> </form> </div> {% endblock %} Now As you can see that I took the inputs in my views.py in the first five fields (name, dob, CNIC, property_type, down_payment), because these are the only fields required to add new client to my database. … -
After deleting python 3.7 and installing 3.9 my python project is showing following error
when i am trying to use virtualenv from terminal by following command workon api "eroor occurs is 'workon' is not recognized as an internal or external command, operable program or batch file. enter image description here -
How to show two tables inline in django admin?
I have created two models in models.py, Product and ProductImage. Product is needed to show a certain product. ProductImage is needed to show multiple images of one Product. Here is the code in models.py : class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) def __str__(self): return self.product.name @property def imageURL(self): try: url = self.image.url except: url = '' return url And here is the code in admin.py : from django.contrib import admin from .models import * # Register your models here. class ProductImageAdmin(admin.TabularInline): model = ProductImage extra = 2 # how many rows to show class ProductAdmin(admin.ModelAdmin): inlines = (ProductImageAdmin,) admin.site.register(ProductAdmin, ProductImageAdmin) I keep getting this error: TypeError: 'MediaDefiningClass' object is not iterable I searched this error but I still did not manage to fix this. I also looked in the documentation (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models) What is the cause of this error? Thank you! -
JWT Logout "detail": "Authentication credentials were not provided."
I am trying to create a Logout endpoint for a jwt token in djangorestframework. When I access this endpoint via postman, I get "detail": "Authentication credentials were not provided." What am I missing here? Am I supposed to create a serializer that has a field for the refresh token and add it to the view? Am I parsing the data corretly in postman? views.py from rest_framework.permissions import IsAuthenticated from rest_framework_simplejwt.tokens import RefreshToken class LogoutView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): try: refresh_token = request.data["refresh_token"] token = RefreshToken(refresh_token) token.blacklist() return Response(status=status.HTTP_205_RESET_CONTENT) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) urls.py from accounts.views.user_api_views import ( LogoutView, LogoutAllView, ) urlpatterns = [ path("auth/", include("djoser.urls")), path("auth/", include("djoser.urls.jwt")), path("auth/token/", ObtainCustomizedTokenView.as_view(), name="token_obtain_pair"), path( "auth/token/refresh/", jwt_views.TokenRefreshView.as_view(), name="token_refresh", ), path("logout/", LogoutView.as_view(), name="logout"), path("logout_all/", LogoutAllView.as_view(), name="logout_all"), ] settings.py INSTALLED_APPS = [ ... # local apps # 3rd party "storages", "rest_framework", "rest_framework_gis", "rest_framework.authtoken", "djoser", "django_celery_beat", "raven.contrib.django.raven_compat", "rest_framework_simplejwt.token_blacklist", ] ...... SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(weeks=521), # 10 years "REFRESH_TOKEN_LIFETIME": timedelta(weeks=521), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "ALGORITHM": "HS256", "SIGNING_KEY": SECRET_KEY, "VERIFYING_KEY": None, "AUTH_HEADER_TYPES": ("JWT",), "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", } ...... REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), "DEFAULT_PARSER_CLASSES": [ "rest_framework.parsers.JSONParser", "rest_framework.parsers.FormParser", "rest_framework.parsers.MultiPartParser", ], "DEFAULT_PERMISSIONS_CLASSES": ("rest_framework.permissions.IsAuthenticated"), } Image from Postman -
Django python variable not printing in html
this is my code in my views.py: import requests import os import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def btc(request): query_url = [ 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=4&interval=daily', ] headers = { } result = list(requests.get(u, headers=headers) for u in query_url) json_data1 = result[0].json() btcprices = [] btcprices.append(int(json_data5['prices'][0][1])) print(btcprices) context = { "btcprices": btcprices, } return render(request, "index.html", context) when i do {{ btcprices }} in my html file nothing apperas on the web page when i "python manage.py runserver" it works with other variables that i removed from the code but i'm struggling with this one. Any idea why ? by the way the print(btcprices) gives me : [59014, 57922, 58243, 58376] it's type is a list of integers -
How to find dictionary by date in dictionary of dictionaries
I have a dictionary of dictionaries, each is a boxscore of a game in a season. If I wanted to pull one specific game by date, how would I pull that one dictionary out? Something like... for game in schedule: boxscore = game.boxscore if date = '2021-03-21' Thanks! def management(request): """ View to return site management page """ schedule = Schedule('CHI') for game in schedule: boxscore = game.boxscore date = game.date date_time_date = datetime.datetime.strptime(date, '%a, %b %d, %Y') game_date = date_time_date.strftime('%Y-%m-%d') context = { 'game_date': game_date, 'boxscore': boxscore, } return render(request, 'management/management.html', context) -
Unable to get logged in username in django
I am trying to get User as foreignkey in a model but getting error. When I try: qr.claimed = True user = get_object_or_404(User,id=request.user.id) qr.branch = user qr.save(); OUTPUT: AttributeError: 'str' object has no attribute 'user' When I try to POST: qr.claimed = True get_user = request.POST.get('branch') user = User.objects.get(id=get_user) qr.branch = user qr.save(); OUTPUT: AttributeError: 'str' object has no attribute 'POST' When I define user in another python file and try to fetch from there: qr.claimed = True get_user = pythonfile.user user = User.objects.get(id=get_user) qr.branch = user qr.save(); OUTPUT: TypeError: Field 'id' expected a number but got <function user at 0x0E777E38>. request.user -> AttributeError: 'str' object has no attribute 'user' request.POST -> AttributeError: 'str' object has no attribute 'POST' Any error with request or missing any package to install/import? -
Celery task with Scikit-Learn doesn't use more than a single core
I am trying to create a an API endpoint that will start a classification task asynchronously in a Django backend and I want to be able to retrieve the result later on. This is what I have done so far: celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings") app = Celery("backend") app.config_from_object("django.conf:settings", namespace = "CELERY") app.autodiscover_tasks() tasks.py from celery import shared_task @shared_task def Pipeline(taskId): # ...read file, preprocess, train_test_split clf = GridSearchCV( SVC(), paramGrid, cv=5, n_jobs = -1 ) clf.fit(XTrain, yTrain) # ...compute the metrics Django view for executing the task: views.py class TaskExecuteView(APIView): def get(self, request, taskId, *args, **kwargs): try: task = TaskModel.objects.get(taskId = taskId) except TaskModel.DoesNotExist: raise Http404 else: Pipeline.delay(taskId) # ... Database updates The problem is the started task only uses one core of the CPU, hence taking a very long time to complete. I also see this error: Warning: Loky-backed parallel loops cannot be called in a multiprocessing, setting n_jobs=1. Is there a way to solve this? I am aware of a similar question on SO made in 2018 that is kind of similar to this, but that post has no definite answer, so I am looking for a solution with no luck so far. … -
Cannot understand error when url is changed in django. It throws '404'
When I first created the urls with 'pk' they worked fine. But when I use 'slug' for lookup, when I change the url it throws 404. url patterns that work Now when I change the 'product-detail' url, the feature url throws error which is irrelevant. And it says that this particular view is causing it. But the view has no relation with 'featured-product-list' url. url pattern that cause error enter image description here On diagnosing it I find that it is trying to pass 'featured' as a slug, which is out of my logic. Please help me to find what is causing this issue. here is the detailed error here is the view -
add tomporary user using forms for appointement application with django
I'm stuck in the attempt to create an appointment application with Django to register (as a patient) and non registered user (doctor makes appointment for non register patient) for the 2ns case (for the non register user) my idea is to create a new user with a type = temporary, but I could not figure out how to add him and specify his type as a temporary using a user form and a profile form to add some information and the appointment form this is my models.py class TypeOfUser(models.TextChoices): PATIENT = 'patient', 'Patient' DOCTOR = 'doctor', 'Doctor' RECEPTION = 'reception', 'Reception' TEMPORARY = 'temporary', 'Temporary' class User(AbstractUser): type_of_user = models.CharField(max_length=200, choices=TypeOfUser.choices, default=TypeOfUser.PATIENT) allowd_to_take_appointement = models.CharField(max_length=20, choices=AllowdToTakeAppointement.choices, default=AllowdToTakeAppointement.YES) def is_doctor(self): return self.type_of_user == TypeOfUser.DOCTOR def is_temporary(self): return self.type_of_user == TypeOfUser.TEMPORARY and this is the forms.py class AppointmentForm_2(forms.ModelForm): doctor = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.DOCTOR)) patient = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.PATIENT)) date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) start_time = forms.DateField(widget=forms.DateInput(attrs={'type': 'time'})) class Meta: model = Appointment fields = ('patient', 'doctor', 'date', 'start_time') class UserEditForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') class ProfileUpdateForm(forms.ModelForm): gender = forms.ChoiceField(choices=GENDER_CHOICES, required=False, widget=forms.RadioSelect) class Meta: model = Profile fields = ('date_of_birth', 'gender', 'phone_number', 'blood_group', 'address', 'photo') and this is the fucntion for register … -
Type Error /login authenticate() takes from 0 to 1 positional arguments but 2 were given
def loginUser(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('pass1') user = authenticate(username, password) if user is not None: login(request, user) return redirect( '/') else: messages.error(request, "Either your email or password is wrong!") return render(request, 'loginpage.html') return render(request, 'loginpage.html') Whenever I enter the credentials on the login page this error appears, my login function is also named loginUser yet -
how to provide foreign key value input through <input> html django , ValueError?
please this is an urgent task i very appreciate to your recommenditions i'm trying to make an online order system , someone can order several items at the same time , for that reason i have used inlineformset and sometimes using {{form.field_name}} prevent some styles and js events , for that purpose i decided to use input fields manually <input> tags , i didnt faced such challenges in my previous projects , now im confused how to achieve it !? this is my models.py class Item(models.Model): items = models.CharField(max_length=50) #others def __str__(self): return self.items class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items = models.ManyToManyField(Item,through='ItemsInvoice') class ItemsInvoice(models.Model): invoice= models.ForeignKey(Invoice,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.IntegerField() i used function based view in view and this is my views.py @login_required def createClientInoiveView(request): item_names = Item.objects.all() if request.method == 'POST': customer = request.POST['customer'] seller = request.user obj = CustomerInvoice.objects.create(seller=seller,customer=customer) # inlineformset fields item = request.POST['items'] quantity = request.POST['quantity'] price = request.POST['price'] cash = request.POST['cash'] discount = request.POST['discount'] items = InvoiceItem.objects.create(item=item,quantity=quantity,price=price,cash=cash,discount=discount) with transaction.atomic(): obj = obj.save(commit=False) if obj.is_valid and item.is_valid(): item.invoice = obj obj.save() item.save() return redirect(reverse_lazy('invoiceapp:detail-invoice',kwargs={'pk':obj.pk})) return render(request,'invoiceapp/create_invoice.html',{'item_names':item_names}) and this is my html form <form method="POST">{% csrf_token %} {{items.management_form}} <div … -
Using JWT authentication with Django/DRF and Storing JWTs in HttpOnly Cookies
I am trying to build a web app using Django and DRF at the back-end and ReactJs at the front end and I want to keep them separate (i.e. avoid Server Side Rendering).For authentication purposes, I want to employ JWT and I am using djangorestframework-jwt for that. I have read it at several places that it is not secure to store JWTs in the local storage so I am trying to use HttpOnly cookies for that. One can achieve that by configuring the django server to send HttpOnly by overriding the following default settings of the drf-jwt package in the settings.py file of your project JWT_AUTH = { 'JWT_AUTH_COOKIE': '<cookie name>', } which is set to none by default. The server sends the httpOnly cookie as anticipated but there are a few issues I am facing: 1.Same Domain Restraint I am aware that httpOnly cookies wont be attached to the request headers unless the request is being made to the server which is hosted on the some domain. In my case I am using localhost:8000 for django and localhost:3000 for my react project so the browser doesnt attach the cookie as the request is made to a different port. I … -
CHARTJS baar chart not showing
i have this js code for a bar chart and i use python data for the yaxis this is my js code : <div class="btcprices-chart"> <canvas id="myChart3"></canvas> <script> var ctx = document.getElementById('myChart3').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'bar', // The data for our dataset data: { labels: ["day1", "day2", "day3", "day4"], datasets: [{ label: 'bitcoin brices per day', backgroundColor: 'rgb(66, 103, 178, 0.6)', borderColor: 'rgb(75, 79, 220))', borderWidth: 2, data: {{ btcprices|safe }} }] }, // Configuration options go here options: { title: { display: true, text: 'bitcoin brices per day' } } }); </script> </div> i have another chart but with nother data values : data=[626830186, 1055315163, 64138356, 314568549] and for this chart btcprices=[59014, 57922, 58243, 58376] in data : {{ btcprices|safe }} it works when i replace it by {{ data[safe }} it works perfectly but if not it shows this : weird bar chart output ps : whn i call the 2 variables data and btcprices in th html just to print them on the web page like : {{data}} and {{btcprices}} only data shows !!!! -
How to select all users I don't follow in Django Models
I'm trying to build web app with Django on my backend and I want to make some type of people recommendations and show only people the current user doesn't follow, however I don't know how to do this. It seems like there are questions on StackOverflow however they are about SQL queries and I still only know the Django Models for the database. I use the standard Django User Model and the following model for the following relationship class Follow(models.Model): # This means following(Person A) follows follower(Person B) following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') def __str__(self): return str(self.following.username) + " follows " + str(self.follower.username) class Meta: unique_together = (('following', 'follower'), ) I use the following query to get all the users the current user follows, but I would like to sort-of invert it. Follow.objects.filter(following=user.id).prefetch_related('following') -
How to reset Django database?
I'd really like to know how to reset Django database. Specifically, I accidentally deleted a table with this command, $ python manage.py dbshell $ DROP TABLE qaapp_question; and everything messed up. I followd a stackoverflow post and just deleted the table, and, haha, completely messed up. syncdb stuff is apparently deprecated so cannot use it. I tried all the ways I googled and found, as followings: $ python manage.py migrate qaapp zero django.db.utils.OperationalError: no such table: qaapp_question Not working. $ manage.py migrate --fake <appname> zero $ rm -rf migrations # I deleted the app migrations folder manually $ manage.py makemigrations <appname> $ manage.py migrate --fake <appname> Not working. $ python manage.py flush Not working. $ python manage.py reset_db Reset successful. Not working. manually trying to delete the sqlite database file -> resource busy or locked Not working. I wanted to restore the deleted table, but I don't care anymore, just kindly tell me how to delete, initialize the database, then be able to rebuild the database with python manage.py makemigrations and python manage.py migrate. Thanks for your help.