Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I track and commit without push?
What I'm trying to do is to version a file without ever pushing it to github, is it something I can do ? Context : For instance, I have a local database for dev (Django) which is SQLite3 which creates a file "db.sqlite3". I don't want this file to be on github, but I'd like to be able to reset it to previous version if I mess with the migrations for example. Maybe they are better ways than git, I'm open to suggestions. Thank you ! -
TypeError at /listing: save() missing 1 required positional argument: 'self'
I'm trying to make an auction site and I'm having an issue changing the bid in the Bids model for a particular Auctionlisting object when POST data is submitted. class Bids(models.Model): minimum_bid = models.DecimalField(max_digits=8, decimal_places=2, null=False) allbids = [] bid = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) allbids.append(bid) numBids = len(allbids) def __str__(self): if self.bid == None: return f"Minimum Bid: ${self.minimum_bid}" else: return f"Highest Bid: ${self.bid}" def save(self, userbid, object): item = self.objects.get(pk=object) item.bid = userbid item.save() Here is my AuctionListing model: class AuctionListing(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=137) category = models.CharField(max_length=10, choices=Category.CHOICES, default="Men") image = models.ImageField(upload_to="media") bid = models.OneToOneField(Bids, on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.category}: {self.title}" Here is how I'm submitting the data in my views: if request.method == "POST": if "userbid" in request.POST: try: userbid = AuctionListing.objects.get(pk = request.GET.get("listing")) userbid.bid = Bids.save(userbid=1000,object=object) userbid.save() except IntegrityError: pass -
Django def _str_(self): return self.fname not working
from django.db import models # Create your models here. class Contact(models.Model): fname = models.CharField(max_length=22) lname = models.CharField(max_length=22) mnumber = models.CharField(max_length=12) eid = models.CharField(max_length=22) date = models.DateField() def _str_(self): return self.fname This is the code, everything is fine, I have already tried everything, no error, still, the def str(self) is not working. Please help me. -
: The term 'git' is not recognized as the name of a cmdlet, function, script file, or operable program.
git : The term 'git' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 git remote add origin https://github.com/rehmat11872/gs9django.git + CategoryInfo : ObjectNotFound: (git:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
i have followed everything from a tutorial but it says unexpected indent on line 6, how can i resolve this [duplicate]
from django.shortcuts import render from .models import Post def post_list_view(request): post_objects = Post.objects.all() context = { 'post_objects' : post_objects } return render(request, "posts/index.html", context) -
how to django template list indexing control
{{ object_list }} # show <img src="{{ object_list.0.photo.url }}"># show object_list[0] {% for i in object_list %} # delete object_list[0] from object_list <img src="{{ i.photo.url }}"> {% endfor %} -
Generate table using raw SQL query and want to use those tables as ORM in Django
table_title = 'transaction_' + username with connection.cursor() as cursor: sql = 'CREATE TABLE ' + table_title + '(id uuid NOT NULL, sql += 'amount numeric(10,2) NOT NULL, sql += 'CONSTRAINT transaction_pkey' + username + ' PRIMARY KEY (id),' cursor.execute(sql) I have create table using this code. Now what I want: I want to use them in the application's admin.py I want show them in Django's admin panel I want to use this table as ORM in views. Is it possible? If yes, then how? -
row count in csv file to database Django
I want to limit the no of rows before importing to db, how I can count the rows of csv file in the following function def user_upload(request): template = "user_upload.html" if request.method == "GET": return render(request, template) try: csv_file = request.FILES['file'] except MultiValueDictKeyError: csv_file = None if csv_file: if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') if csv_file: data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): if len(column) > 10: try: users = User( username=column[0], first_name=column[1], last_name=column[2], email=column[3], add_1=column[4], add_2=column[5], suburb=column[6], city=column[7], state=column[8], postcode=column[9], country=column[10], ) users.set_password('password') users.save() except (IntegrityError, ValueError) as e: return render_to_response('message.html') context = {} return render(request, template, context) else: messages.error(request, 'Please select a valid file!') return redirect('home') The data_set, row count is not giving the right figures, seeking help, thank you -
Disable next button in last imgage in image slider Java script
I'm building an image slider with Java script with next button to toggle between the images. So automatically when reach the last image it begins from the first. I want to disable the next button in last image. or change it with another button like submit or something HTML: <div class="slider"> <!-- fade css --> <div class="myslide fade"> <div class="txt"> <h1>IMAGE 1</h1> <p>Web Devoloper<br>Subscribe To My Channel For More Videos</p> </div> <img src="img1.jpg" style="width: 100%; height: 100%;"> </div> <div class="myslide fade"> <div class="txt"> <h1>IMAGE 2</h1> <p>Web Devoloper<br>Subscribe To My Channel For More Videos</p> </div> <img src="img2.jpg" style="width: 100%; height: 100%;"> </div> <div class="myslide fade"> <div class="txt"> <h1>IMAGE 3</h1> <p>Web Devoloper<br>Subscribe To My Channel For More Videos</p> </div> <img src="img3.jpg" style="width: 100%; height: 100%;"> </div> </div> a class="next" onclick="plusSlides(1)">&#10095;</a> JS: const myslide = document.querySelectorAll('.myslide'), dot = document.querySelectorAll('.dot'); let counter = 1; slidefun(counter); let timer = setInterval(autoSlide, 8000); function autoSlide() { counter += 1; slidefun(counter); } function plusSlides(n) { counter += n; slidefun(counter); resetTimer(); } function currentSlide(n) { counter = n; slidefun(counter); resetTimer(); } function resetTimer() { clearInterval(timer); timer = setInterval(autoSlide, 8000); } function slidefun(n) { let i; for(i = 0;i<myslide.length;i++){ myslide[i].style.display = "none"; } for(i = 0;i<dot.length;i++) { dot[i].className = dot[i].className.replace(' … -
How can I display my in save to create new playlist on side bar in django just like youtube playlist?
The button has now been renamed to "Save," and a single tap will automatically add the video to your most recently selected playlist (or your Watch Later list, if you haven't used the feature before).then my question is how can we display the list on side bar? -
"Attribute error: module "myApp.views" has no attribute symbol " - Django
I'm using django framework for my app backend, I want to use the attribute (fetched using request.get()) from views.py file into another py file into same directory as views.py . I am getting the following two errors. -
Difference between creating custom Django token generator and using the default PasswordResetTokenGenerator
I'm creating a verification email users app, which as the name may suggest verify users' emails before activating their accounts. I've seen in many tutorials that they use the following code to create a custom token generator for account activation: class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return text_type(user.is_active) + text_type(user.pk) + text_type(timestamp) token_generator = TokenGenerator() However, I don't see why I should use this over the default PasswordResetTokenGenerator. I've tried to implement both, the custom and the default and the result is the same. Why do they suggest inheriting PasswordResetTokenGenerator and create an AccountActivationTokenGenerator. Is there any security issue if I use the same token generator for two tasks? -
! [remote rejected] main -> main (pre-receive hook declined)
name@pop-os:~/project/projectname$ git push heroku main Enumerating objects: 521, done. Counting objects: 100% (521/521), done. Delta compression using up to 4 threads Compressing objects: 100% (417/417), done. Writing objects: 100% (521/521), 235.54 MiB | 411.00 KiB/s, done. Total 521 (delta 37), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python- 3.9.6 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.6 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting aniso8601==7.0.0 remote: Downloading aniso8601-7.0.0-py2.py3-none-any.whl (42 kB) remote: Collecting anyascii==0.1.7 remote: Downloading anyascii-0.1.7-py3-none-any.whl (260 kB) remote: Collecting appdirs==1.4.4 remote: Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) remote: ERROR: Could not find a version that satisfies the requirement apsw==3.28.0.post1 (from -r /tmp/build_40fef6ac/requirements.txt (line 4)) (from versions: 3.8.2.post1, 3.8.5.post1, 3.8.6.post1, 3.8.7.1.post1, 3.8.7.2.post1, 3.8.7.3.post1, 3.8.8.1.post1, 3.8.8.2.post1, 3.8.9.post1, 3.8.10.1.post1, 3.8.11.1.post1, 3.9.2.post1) remote: ERROR: No matching distribution found for apsw==3.28.0.post1 (from -r /tmp/build_40fef6ac/requirements.txt (line 4)) remote: ! Push rejected, failed to compile Python app. remote: … -
Django authentication login
I am building a Django app. I have customized the User model. My models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from phonenumber_field.modelfields import PhoneNumberField from phonenumber_field.phonenumber import PhoneNumber # Create your models here. class UserManager(BaseUserManager): def create_user(self, phone_number,username,email=None, password=None): if not phone_number: raise ValueError("You must specify your phone number") if not username: raise ValueError("You must specify your username") try: user = self.model(phone_number= PhoneNumber.from_string(phone_number=phone_number,region="BD").as_national, username=username, email=self.normalize_email(email)) except : user = self.model(phone_number= PhoneNumber.from_string(phone_number=phone_number,region="BD").as_national, username=username) user.save(using=self._db) return user def create_stuffuser(self, phone_number,username,email,password): user = self.create_user(phone_number,username,email=email,password=password) user.staff = True user.save(using=self._db) return user def create_superuser(self, phone_number,username,email,password): user = self.create_user(phone_number,username,email=email,password=password) user.staff = True user.admin= True user.save(using=self._db) return user class User(AbstractBaseUser): phone_number = PhoneNumberField(unique=True) username = models.CharField(unique=False,max_length=50) REQUIRED_FIELDS = ['username'] email = models.EmailField(unique=False) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'phone_number' def get_full_name(self): return self.username def get_short_name(self): return self.username def get_email(self): return self.email def __str__(self): return str(self.phone_number) def has_perm(self, perm, obj=None): return True def has_module_perms(self,app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin objects = UserManager() Now, @login_required is not working. I have tried to authenticate user and login with the built-in authenticate and login function: def loginfunc(response): if response.method == 'POST': ph = response.POST['ph'] pw = … -
Local settings not found : ModuleNotFoundError: No module named 'account'
I'm getting error in cmd : ModuleNotFoundError: No module named 'account' Below is my code in which i am facing some issue please help and suggest me any change needed in command or the codeenter image description here import account.form from django import forms class SignupForm(account.forms.SignupForm): def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) del self.fields["username"] class UploadFileForm(forms.Form): file = forms.FileField() -
Django: Can't fetch records for the current date
I know you might be thinking that this is some stupid & trivial question by reading the heading but I can't make it work. I have one model called Survey which has one field called survey_date which is of type DATE. What I want to do is that fetch all the records by today's date & I really don't know why this easy looking thing became the pain in the a**. The simplest way I tried was this, def get_initial_queryset(self): today = datetime.date.today() qs = Survey.objects.filter(survey_date=today) print(qs.query) return qs I thought this should work but it did not, So tried googling it and found this Query datetime by today's date in Django It was very similar to my problem but believe me I tried every single answer from it and nothing worked. I even tried to get the actual query from the queryset I tried to run it manually via phpmyadmin but it returned no rows.I am pasting that generated query also here(I made it little shorter by removing other columns), SELECT `survey`.`id`, `survey`.`uid`, `survey`.`currency`, `survey`.`survey_type`, `survey`.`survey_subtype`, `survey`.`transit_type`, `survey`.`survey_date`, `survey`.`survey_time`, `survey`.`live_survey_type` FROM `survey` WHERE `survey`.`survey_date` = 2021-08-17 Any help would appreciated.I am using Django version 3.1.6. -
How to auto populate a read-only serializer field in django rest framework?
I have a question regarding django rest framework. Most of the time, I have a serializer which has some read-only fields. For example, consider this simple model below: class PersonalMessage(models.Model): sender = models.ForeignKey(User, related_name="sent_messages", ...) recipient = models.ForeignKey(User, related_name="recieved_messages", ...) text = models.CharField(...) def __str__(self) -> str: return f"{self.text} (sender={self.sender})" In this model, the value of sender and recipient should be automatically provided by the application itself and the user shouldn't be able to edit those fields. Alright, now take a look at this serializer: class PersonalMessageSerializer(serializers.ModelSerializer): class Meta: model = PersonalMessage fields = '__all__' read_only_fields = ('sender', 'recipient') It perfectly prevents users from setting an arbitrary value on the sender and recipient fields. But the problem is, when these fields are marked as read-only in the serializer, the serializer will completely ignore all the values that are passed into the constructor for these fields. So when I try to create a model, no values would be set for these fields: PersonalMessageSerializer(data={**request.data, 'sender': ..., 'recipient': ...) # Won't work What's the best way to prevent users from setting an arbitrary value and at the same time auto-populate those restricted fields in django rest framework? -
Django error when trying to migrate models with foreignkeys that don't have null=True or default set
I have this model that is a post like on Twitter, that has a creator. I'd ideally like the post to always require a creator_id and if the creator gets deleted then delete the post as well class Post(AbstractBaseModel): creator_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post_creator_id") body = models.CharField(max_length=511) Whenever I try to run 'python manage.py migrate' I get this error "You are trying to change the nullable field 'creator_id' on cheerpost to non-nullable without a default; we can't do that (the database needs something to populate existing rows)." The options to solve this are are 1) provide a one off default or 2) ignore for now. Neither of these seem to fulfill my constraint that I want to enforce, which is creator_id must exist and is the person who created the post or the entity gets deleted. -
How does a django project use multiple databases with the same structure to read and write, distinguished by url
I have a django project and want to divide it into multiple databases with the same structure. Use url to distinguish different databases. When the admin management page logs in, log in to different databases according to different urls. For example: 127.0.0.1/admin uses the admin database, 127.0.0.1/admin2 uses the admin2 database. Does django implement this function? What do I need to do, Can you give me some suggestions or ideas? thank you very much -
Stripe Integration with Django giving a type error saying __init__() takes 1 positional argument but 2 were given
Hi I've been trying to learn how to integrate the Stripe prebuilt checkout page into my django project. The stripe docs are for flask so I'm trying to read or watch youtube tutorials on how to convert them into django but I'm not really getting anywhere. The code in the tutorials are different from the current stripe docs https://stripe.com/docs/checkout/integration-builder from django.shortcuts import render, redirect import stripe from django.conf import settings from django.http import JsonResponse # Create your views here. from django.views import View from django.views.generic import TemplateView stripe.api_key = settings.STRIPE_SECRET_KEY class ProductLandingPageView(TemplateView): template_name = "landing.html" class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { # TODO: replace this with the `price` of the product you want to sell 'price': '{{PRICE_ID}}', 'quantity': 1, }, ], mode='payment', success_url=YOUR_DOMAIN + "/success", cancel_url=YOUR_DOMAIN + "/cancel", ) return redirect(checkout_session.url, code=303) class Successview(TemplateView): template_name = "success.html" class Cancelview(TemplateView): template_name = "cancel.html" I can get the checkout.html to show but when I click on the checkout button I get this error TypeError at /create-checkout-session __init__() takes 1 positional argument but 2 were given Request Method: POST Request URL: http://127.0.0.1:8000/create-checkout-session Django Version: 3.2.5 Exception Type: TypeError Exception Value: __init__() takes 1 … -
checkbox inputs are only submitted when is checked
This is my first Django project I have this simple form which I would like to submit all row values (checked or unchecked), The error I am facing is that it only sends row{num} value if it is checked. <script> function calc(elemId) { var elem = document.getElementsByName(elemId)[0]; if (elem.checked) { elem.value = 1; } else { elem.value = 0; } } </script> <div class="container pt-3"> <form action="." method="post"> <table class="table table-hover"> <thead> <tr> <th scope="col">#</th> <th scope="col">Keyword</th> <th scope="col">seller_items</th> <th scope="col">Total</th> <th scope="col">checked</th> </tr> </thead> {% csrf_token %} {{ form|crispy }} {%for i in data%} <tr > <th scope="row">{{forloop.counter}}</th> <td>{{i.keyword}}</td> <td>{{i.seller_items}}</td> <td>{{i.total_found}}</td> <td> {% if i.checked %} <input type="checkbox" name="row{{i.id}}" value="1" checked="checked" onclick="calc('row{{i.id}}')"/> {%else%} <input type="checkbox" name="row{{i.id}}" value="0" onclick="calc('row{{i.id}}')"/> {%endif%} </td> </tr> {% endfor %} </table> <div class="row"> <div class="col-12"> <button class="btn btn-primary float-right" type="submit">Update</button> </div> </div> </form> the form is submitted when the button is pushed but only checked boxes rows are in the post request -
This code is the part of my Django project, my task is to find company name from the job description parsing, but I am unable to get the company name?
from .CleanJdTextData import Cleaned_Text, ReadModule from resume_app.Config_Reader import Config_Dict from jd_app.Designation_Extract import Designation_Extract nlp_Company_Module = ReadModule(Config_Dict['company_aliases_resume_parsing']) nlp_designation_module = ReadModule(Config_Dict['designation_saveLoc']) added class CompanyExtract(): def __init__(self, cleaned_data, nlp_cn): self.cleaned_data = cleaned_data self.nlp_cn = nlp_cn def company_extract(self): company_designation_dict = dict() if all([self.cleaned_data, isinstance(self.cleaned_data, tuple)]): try: area_to_search = self.cleaned_data[:10] except: area_to_search = self.cleaned_data area_to_search = self.cleaned_data for index, data in enumerate(area_to_search): # for data in area_to_search: company_data = self.apply_Nlp_On_Data(data) if any([company_data]): company_designation_dict.update({'company_name':company_data}) designation = Designation_Extract(self.cleaned_data, nlp_designation_module()).extract_designation(index) if any([designation]): company_designation_dict.update({'designation':designation}) return company_designation_dict def lemma_Add_In_data(self, str_data): lemma_add = ' '.join([x.lemma_ if x.text != "limited" else x.text for x in self.nlp_cn(str_data)]) data = [str_data, lemma_add] if lemma_add != str_data else [str_data] if any([data]): return data def replace_Pvt_Ltd(self, str_data): if all([str_data, isinstance(str_data, str)]): replace_dict = {"pvt": "private", "ltd": "limited", "co":"company", "inc":"incorporated", "corp": "corporation"} data = ' '.join([replace_dict[x] if x in replace_dict.keys() else x for x in str_data.split()]) if any([data]): return self.lemma_Add_In_data(data) def apply_Nlp_On_Data(self, str_data): if all([str_data, isinstance(str_data, str)]): replace_pvt_ltd_ = self.replace_Pvt_Ltd(str_data) if any([replace_pvt_ltd_]): for company_name in replace_pvt_ltd_: doc = self.nlp_cn(company_name) company_name_s = [x.text.title() for x in doc] if any([company_name_s]): return company_name_s[0] class ExtractCompanyName: def init(self, text_data): self.text_data = text_data def extract_company_name(self): if all([self.text_data, isinstance(self.text_data, tuple)]): company_designation_dict = dict() global obj_Of_clean_Data obj_Of_clean_Data = Cleaned_Text(self.text_data, ['+', '&']) company_designation_dict = CompanyExtract(obj_Of_clean_Data(), … -
Django - Ensure 2 fields in a table of the same model type don't have the same value for an entity
So I have a user class and a user can follow another user, but I don't want the user to be able to follow themselves. Is there a way to add this constraint to Django? class FollowUser(AbstractSimpleModel): follower_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower_id') followee_id = models.OneToOneField(User, on_delete=models.CASCADE, related_name='followee_id') -
Input Variable for Slice in html Forloop - Django
I have a Django website and in one of the HTML files I have a for-loop with a slice functionality to display just the attributes within the slice range. {% for post in filter.qs|slice:"2:11" %} <div class="title">Morgan Hall</div> <div class="inspection_num">Inspection #</div> <div class="inspect_num">{{ post.count_building }}</div> <div class="inspection_date">Inspection Date</div> <div class="current_date_small" id="myDiv"></div> {% if post.image %} <img class="pdf_field_img" src="{{ post.image.url }}"/> {% else %} {% endif %} {% endfor %} I need to have the users have a simple integer input on the same page that defines the range the slice will be at. The input will basically fill a variable in the slice values and define it that way. I have been working on this for a long time with no luck, It is very far beyond me. Any help is greatly appreciated. Thanks! -
STUN/TURN server configuration for Django channels with WebRTC
I developed using django channels to implement video chat and message chat.(I was referring to a YouTuber's course.) When I first completed the development, I noticed that webrtc works only in the local network, and I found out that a stun/turn server was needed. So, I created a separate EC2 and built the stun/turn server and set this to the RTCPeerconnection in the web server. Stun/turn server test in Trickle ICE is good. But My video call still works only within the local network. And even within the same network, the connection was very slow. Server overall configuration.(Webserver with SSL application loadbalancer) Coturn config # /etc/default/coturn TURNSERVER_ENABLED=1 # /etc/turnserver.conf # STUN server port is 3478 for UDP and TCP, and 5349 for TLS. # Allow connection on the UDP port 3478 listening-port=3478 # and 5349 for TLS (secure) tls-listening-port=5349 # Require authentication fingerprint lt-cred-mech server-name=mysite.com realm=mysite.com # Important: # Create a test user if you want # You can remove this user after testing user=myuser:userpassword total-quota=100 stale-nonce=600 # Path to the SSL certificate and private key. In this example we will use # the letsencrypt generated certificate files. cert=/etc/letsencrypt/live/stun.mysite.com/cert.pem pkey=/etc/letsencrypt/live/stun.mysite.com/privkey.pem # Specify the allowed OpenSSL cipher list for TLS/DTLS connections …