Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generate CSV while saving the django Model
In my django model I have start and end date once I filled and then click the generate button (Save modified as Generate) It will save and download the data as CSV. In my case I have done all the parts but the csv is not downloaded because the form is reloaded and then come back to list data page. I want to download the csv file after data saved. -
How to install Django on existing AWS Lightsail instance?
I'm looking for a replacement for Webfaction, which can no longer support Ghost or Django sites. I've picked AWS Lightsail as the pricing seems competitive and the documentation friendly. I've set up a Lightsail instance with Ghost pre-installed and successfully migrated my Ghost instance over there. However, I'd now like to migrate an existing Django site there and I'm not sure: Is it possible to have multiple sites with different URLs running on the same Lightsail instance? Can I add Django to an existing Lightsail instance using the Bitnami clickable installer, or will I need to install it from the command line? The documentation isn't clear. -
Why is My Django Project Hosting Static From myproject/static/django_restframework?
I am trying to access a script file in one of my templates and it is not loading in the template (default.html): <!DOCTYPE html> <html> <head> {% load static %} <script type="text/javascript" src="{% static 'static/js/main.js' %}"></script> <meta charset="utf-8" /> <title>Add a GeoJSON line</title> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no> <style> body { margin: 0; padding: 0; } #map { position: absolute; top: 0; bottom: 0; width: 100%; } </style> </head> <body> </body> </html> The path to static defined in settings.py is: STATIC_URL = '/static/' STATIC_ROOT = '/Users/me/dbapi/static' I have run collectstatic but the folder that the site gets the static files from is inside a folder called rest_framework, (located at /User/me/dbapi/static/rest_framework) which is not part of the path in settings.py. So in addition to not serving my files inside the static folder (which is located at /Users/me/dbapi/static/) it is choosing to only serve files from a path that is not defined in settings.py. Can anyone help me understand this? Here is my settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
How to preview two queries in a autocomplete select2 dropdown
I have an autocomplete select2 dropdown as my django form field like bellow: which the form code is like below: class categories_form(forms.ModelForm): categories = forms.ModelChoiceField( queryset= categories.objects.none(), widget= autocomplete.ModelSelect2( url='load_categories', attrs={ 'data-placeholder': 'Select a category', 'data-html': True, 'style': 'min-width: 15em !important;', } ) ) class Meta: model = Post fields = ['categories'] def __init__(self, *args, **kwargs): super(category_form, self).__init__(*args, **kwargs) self.fields['categories'].queryset = categories.objects.all() But I what to add sub category to the same form, something like below which I took from select2: But I have no idea how to add another query to the form and handle it in template!! -
AttributeError at /products/1/buy/ 'OrderForm' object has no attribute 'save'
Im trying to build a django form for placing orders in my ecommerce website. But, when I press the Place Order button, I get this traceback error: Internal Server Error: /products/1/buy/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\apnibakery\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dell\Desktop\Django\apnibakery\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dell\Desktop\Django\apnibakery\bakery\apnibakeryy\views.py", line 33, in buy form.save() AttributeError: 'OrderForm' object has no attribute 'save' [07/Dec/2020 14:06:34] "POST /products/1/buy/ HTTP/1.1" 500 64996 Here is my OrderForm: class OrderForm(forms.Form): name = forms.CharField(max_length=30) email = forms.EmailField() address = forms.CharField(widget=forms.Textarea()) zip_code = forms.CharField(min_length=6,max_length=6) My view function that handles the orders: def buy(request,id): product = Product.objects.get(id=id) form = OrderForm() if request.method == 'POST': form = OrderForm(data=request.POST) if form.is_valid(): form.save() return HttpResponse("Your order has been successfully placed!!") context = { 'form':form, 'product':product, } return render(request, 'buy_page.html',context) I have never ran into this error before. Can someone help me out? -
How to migrate django users to firebase when the rounds are too high?
I'm looking to migrate user from Django to firebase, below is the code I'm using for testing. The issue I'm facing is that it seems that the passwords have been hashed using 150k rounds when the firebase docs says the maximum is 120k for SHA256: https://firebase.google.com/docs/auth/admin/import-users#python Is there an alternative? Here is the error I get: ValueError: rounds must not be larger than 120000. import firebase_admin from firebase_admin import auth, exceptions from passlib.utils import to_bytes server_path = '' fb_credentials = firebase_admin.credentials.Certificate(server_path + 'files/serviceAccount.json') firebase_admin.initialize_app(fb_credentials) old_hash = 'pbkdf2_sha256$150000$rsWX3Dbbd3K6$EYgXPBAz/Ero9PIgIFs/8pWGmGT+diTOQs1DZv4Ytjw=' email = 'user@gmail.com' rounds = int(old_hash.split('$')[1]) salt = old_hash.split('$')[2] users = [ auth.ImportUserRecord( uid='70sSUptkmkN95QTFJ0gWduzdlpP1', email=email, password_hash=to_bytes(old_hash), password_salt=to_bytes(salt) ), ] hash_alg = auth.UserImportHash.pbkdf2_sha256(rounds=rounds) try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) -
Distinct element of foreign key in django ORM using annotate
I'm having three models . Here is the model structure class Product: size = models.CharField(max_length=200) class Make: name = models.CharField(max_length=200) product = models.ForeignKey(Product) class MakeContent: make = models.ForeignKey(Make) I am having a chart for that I am fetching the query like this qs = Make.objects.values('product__size').annotate( count=Count('product__size') ) // Here I'm getting data count as 65 only .... That's correct also How do I change query from the model MakeContent I have tried this qs = MakeContent.objects.values('make__product__size').annotate( count=Count('make__product__size'), ) // Here I'm getting data as 420 .... But it should be 65 or less than 65.... Because I need the product_size data of Table Make from Table MakeContent -
Should django health-check endpoint /ht/ be accessible from everybody?
From the documentation reported here I read This project checks for various conditions and provides reports when anomalous behavior is detected.The following health checks are bundled with this project: cache, database, storage, disk and memory utilization (viapsutil), AWS S3 storage, Celery task queue, Celery ping, RabbitMQ, Migrations and from use case section The primary intended use case is to monitor conditions via HTTP(S), with responses available in HTML and JSONformats. When you get back a response that includes one or more problems, you can then decide the appropriate courseof action, which could include generating notifications and/or automating the replacement of a failing node with a newone And then The /ht/ endpoint will respond aHTTP 200 if all checks passed and a HTTP 500 if any of the tests failed. From a security point of view: should this url (https://example.com/ht) be reachable from everybody? It seems to give away different information. -
Serving Video with DRF
I almost looked for every possible source but is not satisfied or not found optimum way or path. Actually i have to build a netflix clone (not exactly but a video on demand platform for one local client). The tech stack will be React at the frontend and DRF (Django Rest Framework) at the backend. I know the node will match my purpose at best, but this needs to be done on DRF. How should I return the video, should I return it in bytes, packets and what can sample code look like, how frontend should fetch it. It will really help if you put your insight, in general. Thank you -
Django custom ID field with if condition
I am going to set the custom id with the name of "membership_num" with the increment number by 1, in every new register athlete with a prefix for each record like: if the "goal field in model" is "gym" it should generate the ID: description: N-Gym-Year Month Day then the number N-G-20120700001 N-G-20120700002 N-G-20120700003 if the "goal field in model" is "fitness" it should generate the ID: description: N-Gym-Year Month Day then the number N-F-20120700001 N-F-20120700002 N-F-20120700003 Models.py class Athlete(models.Model): first_name = models.CharField(max_length=50) membership_num = models.CharField(max_length=255, blank=True, editable=False) goal = models.CharField(max_length=10, choices=[('gym', 'Gym'), ('fitness', 'Fitness')]) I found and tried the following solution in stackoverflow but it does not generate the correct ID... def save(self, *args, **kwargs): # super().save(*args, **kwargs) if not self.membership_num: prefix = 'N{}'.format(timezone.now().strftime('%y%m%d')) prev_instances = self.__class__.objects.filter(membership_num__icontains=prefix) if prev_instances.exists(): last_instance_id = prev_instances.last().membership_num[-4:] self.membership_num = prefix + '{0:04d}'.format(int(last_instance_id) + 1) else: self.membership_num = prefix + '{0:04d}'.format(1) super(Athlete, self).save(*args, *kwargs) please help me.... -
TemplateDoesNotExist at / in django
enter image description here from .shortcuts import render from .models import Post Create your views here. def list_of_post(request): post = Post.objects.all() template = 'post/list_of_post.htenter code hereml' context = {'post': post} return render(request, template, context) It should work. -
Django - can't get modelchoice FK while submitting form
I have a custom form form signup, referencing a "categorie" model on a modelChoiceField. As I try to submit it, it fails on getting the reference to the model and raises the following error : IntegrityError at /marketplace/signsupplier/ null value in column "categorie_id" violates not-null constraint DETAIL: Failing row contains (55, , , , , , null). It's as if it loses all posted datas, but I can see in the debug that categorie_id is well passed in the POST datas. Here is my model.py : class Supplier(models.Model): phone_regex = RegexValidator(regex=r'^(87|89)\d{6}$', message="Entrez un numéro de portable Polynésien valide") user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) enseigne = models.CharField(max_length=128, blank=False, null=False) vini = models.CharField(verbose_name="Vini",validators=[phone_regex], max_length=8, blank=False, null=False) numero_tahiti = models.CharField(max_length=9, blank=False, null=False) immat_rcs = models.CharField(max_length=9, blank=False, null=False) categorie = models.ForeignKey(Categorie, on_delete=models.DO_NOTHING) labels = models.CharField(max_length=128) my forms.py : class SignupSupplierForm(UserCreationForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True,label="Prenom") last_name = forms.CharField(required=True,label="Nom") vini = forms.CharField(required=True, max_length=8,validators=[phone_regex]) enseigne = forms.CharField(required=True, max_length=128, label="Enseigne") numero_tahiti = forms.CharField(required=True, max_length=9, label="Numéro Tahiti") immat_rcs = forms.CharField(required=True, max_length=9, label="Immatriculation RCS") categorie = forms.ModelChoiceField(required=False,queryset=Categorie.objects.all()) labels = forms.CharField(required=False,max_length=128, label="Labels (option)") class Meta(UserCreationForm.Meta): model = User fields = ('email','first_name','last_name') @transaction.atomic def save(self): user = super().save(commit=False) user.is_supplier = True user.save() supplier = Supplier.objects.create(user=user) supplier.vini = self.cleaned_data.get('vini') supplier.enseigne = … -
how to host Django Web application on Apache or wamp? [closed]
I have created simple django web application but I don't want to host it on third party server(heroku, pythonanywhere.com). I want to host it on apache server on intranet. How can I do it? -
"rest_framework CSRF token failed" but it's already in the request header as "X-CSRF-Token"
Already checked other topics and tried the answered solutions but the problem stays still. My put/post requests are return with an error. detail: "CSRF Failed: CSRF token missing or incorrect." Although I am sending CSRFToken inside the header axios.defaults.headers.common['X-CSRF-Token'] = CSRF_TOKEN; And there it is the CSRF By the way, in settings.py I gave the authentication classes 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], Additionally views.py class ProjectViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated | IsSuperUser] # retrieve works without a problem def retrieve(self, request, pk=None): queryset = Project.objects.all().filter(company_user=self.request.user) project = get_object_or_404(queryset, pk=pk) serializer = ProjectSerializer(project) return Response(serializer.data) def update(self, request, pk=None): # CSRF request problem pass def partial_update(self, request, pk=None): # CSRF request problem pass and urls.py router = DefaultRouter() router.register('project', views.ProjectViewSet, basename='project') urlpatterns = router.urls Do I missing something here? Why do I keep having the CSRF error? -
Understanding request.data in djnago view
I tried looking at different resources on the internet regarding this request and request.data in django, but I couldn't fully understand it. Why this request parameter is kept inside the function? What are we passing in this request parameter?? Also, what does this request. data do?? def index(request): content = { 'Blogdata': Blog.objects.all(), } return render(request, 'index.html', content) def somefunction (request): data=request.data As you can see I have two functions above both of them have request paramter inside the function. Also, I need the explanation on this request.data as this has to be used multiple times. -
Email is not sending in django after deploy in Cpanel
I just deploy a Django web app in Cpanel. But SMTP email is not working in Cpanel. It works only on my local machine. I don't have much knowledge about Cpanel. Here is my code for setting.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'my gmail' EMAIL_HOST_PASSWORD = 'password' -
django channel async consumer stop receiving after call non-stop function
this is the function thats call inside async consumer ,after it listen_some_change() is called ,it stops receiving new message def listen_some_change(self): #self.get_volume() conn = psycopg2.connect(user=DB_USER,password=DB_PASSWORD,host=DB_HOST, port=DB_PORT,database=DB_DATABASE) curs = conn.cursor() curs.execute("LISTEN some_changes;") seconds_passed = 0 while True: conn.commit() if select.select([conn],[],[],5) == ([],[],[]): seconds_passed += 5 #print ("{} seconds | mydevices_volume_change notification ...".format(seconds_passed)) else: conn.poll() conn.commit() while conn.notifies: notify = conn.notifies.pop() payload = json.loads(notify.payload) print(payload) -
How to save MantToMany filed attribute in databse?
I am making an api in django rest framework. I have created three models in Linkeddata, Individuals group, Event. I have another model Keybase which is another app and have ManyToMany relation with Individual, group and Event. Linked data is in ManyToMany Relation with Individual group and event. While adding data in database,I came to a problem where I dont know How I should save keybase and LinkedData data in Individual, Group and Event table. Here is my code: models.py from django.db import models from account_management.models import User from django.utils import timezone from keybase_management.models import Keybase from django.utils.translation import gettext as _ from django.contrib.postgres.fields import ArrayField import datetime from .validators import validate_event_date, validate_expiry_date # Create your models here. GENDER = [('male', _('Male')), ('female', _('Female')), ('other', _('Other'))] class LinkedData(models.Model): type = models.CharField(default='', max_length=225) query = models.CharField(default='', max_length=225) data = models.JSONField(default={'key': 'value'}) class Portfolio(models.Model): class Meta: abstract = True user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=225, default='') created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) expire_on = models.DateTimeField(default=timezone.now() + datetime.timedelta(hours=1), validators=[validate_expiry_date]) # targets=models.ForeignKey() keybase = models.ManyToManyField(Keybase) linked_data = models.ManyToManyField(LinkedData) addresses = ArrayField(models.CharField(default='null', max_length=225)) phone_numbers = ArrayField(models.CharField(default='0', max_length=11)) descriptions = ArrayField(models.CharField(default='null', max_length=225)) def __str__(self): return self.title @staticmethod def get_all_portfolios(): pass def create_portfolio(self): pass def add_phone_numbers(self): … -
how to make sub pages url in django
In my online store django project, I want to create a sub-page which shows the details of a product that is listed in a page. in urls.py I created the urls for both pages like bellow: path('wwqm', views.water_quality_sensor , name='wwqm'), path('wwqm/<str:water_sensor_title>', views.water_sensor_item, name='water_sensor_item'), in this scenario, a bunch of items are being shown in wwqm. user click on a product and the water_sensor_item should load up. I know its not important but here is views.py: def water_quality_sensor(request): queryset_list = Water_quality_sensor.objects.order_by('-product_name').filter(is_published=True) context = { 'water_quality_sensor': queryset_list, } return render(request, 'products/water_quality_sensor.html', context) def water_sensor_item(request, water_sensor_title): water_sensors = get_object_or_404(Water_quality_sensor, title=water_sensor_title) context = { 'water_sensors': water_sensors } return render(request, 'products/water_sensor_item.html' , context) I try to build the url for each item based on a parameter that is passed to its view(products title). In my templates, I try to create a link like the following: <a href="{% url 'water_sensor_item' w_q_sensor.title %}" class="card hoverable mb-4 text-dark" > one my products' title is 3725. when I click on that product in the main page, I get the following error: Django Version: 3.1.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'water_quality_sensor' not found. 'water_quality_sensor' is not a valid view function or pattern name. What am I doing wrong? -
How to fetch database data based on dropdown selected value in Django?
I uploaded questions into database with dropdown values like PAPER1, PAPER2 etc.., In my template page if i click on PAPER1 i should get only PAPER1 questions. How to fetch the data like that? please help me. models.py: class Questions(models.Model): paper = models.CharField(max_length=10, default='None') qs_no = models.IntegerField(default=None) question = models.TextField(max_length=500) option_a = models.CharField(max_length=100) option_b = models.CharField(max_length=100) option_c = models.CharField(max_length=100) option_d = models.CharField(max_length=100) ans = models.CharField(null=True, max_length=50) forms.py: PAPER_CHOICES = ( ('default', 'None'), ('paper1','PAPER1'), ('paper2','PAPER2'), ('paper3','PAPER3'), ('paper4','PAPER4'), ('paper5','PAPER5'), ('paper6','PAPER6'), ('paper7','PAPER7'), ('paper8','PAPER8'), ('paper9','PAPER9'), ('paper10','PAPER10'), ) class QuestionsForm(forms.ModelForm): paper = forms.CharField(widget=forms.Select(choices = PAPER_CHOICES)) class Meta: model=Questions fields=[ 'paper', 'qs_no', 'question', 'option_a', 'option_b', 'option_c', 'option_d', 'ans', ] views.py: def render_questions(request): print(f'user in render_questions is {request.user.username}', flush=True) if not request.user.is_authenticated: return render(request, 'login.html') else: global exam_session exam_session = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) print(f"session id in render ques is {exam_session}", flush=True) questions = Questions.objects.all() ques = [] qs_no = 1 for q in questions: que = {} que['qs_no'] = qs_no qs_no = qs_no + 1 que['question'] = q.question que['id'] = q.id que['option_a'] = q.option_a que['option_b'] = q.option_b que['option_c'] = q.option_c que['option_d'] = q.option_d ques.append(que) print(f"ques: {ques}", flush=True) return render(request, 'report.html', {'ques': ques}) template.html: <form id="myform" name="myform" action="answer" method="POST"> {% csrf_token %} <div class="questionContainer"> … -
How to change Div width with scroll
I have a contact form towards the bottom of my webpage and I would like to run an animation each time the form section of my webpage is viewed. I have been successful in running it, however I would like to run a second animation when scrolling away from the form. The animation is just an underline underneath the contact tab. The result I am trying to achieve is increasing the width of the underline (contact tab) when contact form is viewed and decreasing the underline width when scrolling away from it. I have created two separate ccs files to call when needed. Here is my code. css files (increase width animation) underLineAnimate.css #contactLink{ background-image: linear-gradient(#00bbcb, #00bbcb); background-position: bottom center; /*Adjust the background-position to move the line*/ background-size: 60% 2px; /*Adjust the background size to control length and height*/ background-repeat: no-repeat; padding-bottom: 4px; /* this can also control the position */ animation-name: forContactL; animation-duration: 2s; } @keyframes forContactL { from {background-size: 10% 2px;} to {background-size: 60% 2px;} } decrease width animation underLineDecrease.css #contactLink{ background-image: linear-gradient(#00bbcb, #00bbcb); background-position: bottom center; /*Adjust the background-position to move the line*/ background-size: 0% 2px; /*Adjust the background size to control length and height*/ background-repeat: no-repeat; … -
Django 500 (Internal Server Error). Failed to load resource. Javascript
Working on Django project. I'm trying to implement the follow button like on Instagram. I'm trying to send fetch request when I press the follow button and update the followers count on the back end. and later get a response on the updated count and update the innerHtml on the page. but I'm getting the following error. if someone can help me out if would be great. index.js:13 Fetch failed loading: POST "http://127.0.0.1:8000/follow". It is showing error below in fetch code failed to load resource: the server responded with a status of 500 (Internal Server Error) Here is my code: URL path("follow", views.follow, name="follow"), Model class User(AbstractUser): followersCount = models.IntegerField(blank=True) followingCount = models.IntegerField(blank=True) def __str__(self): return f"{self.username}" class FollowList(models.Model): userName = models.CharField(max_length=64) followersList = models.ManyToManyField(User, blank=True, related_name="followers") followingList = models.ManyToManyField(User, blank=True, related_name="following") View: @csrf_exempt @login_required def follow(request): # Composing a new email must be via POST if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) # get data user = request.user currentUser = user.username a = User.objects.get(username = currentUser) data = json.loads(request.body) user_name = data.get("username") b = User.objects.get(username= user_name) status = data.get("status") try: a1 = FollowList.objects.get(username=currentUser) b1 = FollowList.objects.get(username=user_name) except FollowList.DoesNotExist: a1 = FollowList(username=currentUser) b1 = FollowList(username=user_name) a1.save() b1.save() … -
Subtract tags in Django
Im been wondering if it is possible to subtract two tags variable in Django something like this, thanks for the help {% for user_information in values.qs %} <td>{{user_information.amount|floatformat:2|intcomma}} - {{user_information.amount_paid|floatformat:2|intcomma}} </td> {% endfor %} -
How to add a unique code for every classroom in django
So, I am trying to build a simple elearning platform with django. What I want to achieve is that for every classroom that a teahcer creates, a unique 6 digit code is also generated, and when a student enters that code, he is admitted inside the classroom. I have a classroom model like this: class Classroom: name = models.CharField(max_length=20) code = models.IntegerField() def __str__(self): return self.title I really don't think an IntegerField would do the work here. Can anyone help me out? -
How do i filter specific set of data from mongo db using django
I need to fetch states list based on country id. The following code is working states_query = States.objects.all() states_result = StatesSerializer(states_query, many=True) but when i use states_query = States.objects.all().filter(country_id=id) states_result = StatesSerializer(states_query, many=True) it is not fetching the results. I am new to mongo db. Please help me with this. Thanks in advance