Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I test the database read/write time in Django?
I need to prototype a basic website in Django and test the read and write speed of the database using the default Sqlite. I will have just one button on the website and when pressed, I want the to obtain the time it took for the database to process the button press. How can I do this? -
I'm trying to add an attribute to the object I've created in Django shell to create some queries but it says the object is not itrable
I'm trying to make a project with django I've migrated the model successfully and when I want to add account number to my checkingaccount objects it says the object is not iterable everything else works properly(as I tested) this is the models.py: from django.db import models # Create your models here. class Bank(models.Model): name = models.CharField(max_length=300) def __str__(self) -> str: return self.name class BankAccount(models.Model): bank = models.ForeignKey(Bank, on_delete=models.CASCADE) balance = models.DecimalField(max_digits=18, decimal_places=2) account_number = models.IntegerField() types = ( ('c', 'checking account'), ('s', 'savings account'), ) type_selection = models.CharField('account type', max_length=1, choices=types ) def __str__(self) -> str: return str(self.account_number) class CheckingAccount(models.Model): balance = models.DecimalField(max_digits=18, decimal_places=2) date_created = models.DateField() last_transaction = models.DateField() account_number = models.ManyToManyField(BankAccount) def __str__(self) -> str: return self.account_number def deposit(cash, self): self.balance += cash def check_balance(self): return self.balance def withdrawal(self, cash): self.balance -= cash class SavingsAccount(models.Model): balance = models.DecimalField(max_digits=18, decimal_places=2) date_created = models.DateField() account_number = models.ManyToManyField(BankAccount) def __str__(self) -> str: return self.account_number def deposit(cash, self): self.balance += cash def check_balance(self): return self.balance this is the shell input and output: >>> acC.account_number.set(ac) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Armin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py", line 992, in set objs = tuple(objs) TypeError: 'BankAccount' object is not iterable any helps … -
how i can solve these issue in vscode and django framework
here in my viwes.py I tried to select recommended python interpreter but nothing happen Import "rest_framework" could not be resolved -
Paypal Sandbox not sending IPN back to django through ngrok tunnel, but works fine on IPN Simulator
I have a django app that uses django-paypal to manage payments and trigger certain actions using signals.py when the payment is received @receiver(valid_ipn_received) def payment_notification(sender, **kwargs): ipn = sender if ipn.payment_status == 'Completed': # payment was successful, do something In order to test it locally, I'm using ngrok to expose the local server to Paypal services. Using the IPN Simulator everything is working fine and the signal in the django platform is triggered. However, when I interact with the sandbox under the same conditions, I am not receiving the IPN back from Payal after the payment is completed. From the sandbox business account dashboard I can see the payment is received, but looking at the IPN History from the same account I notice that Paypal is not able to send the IPN, claiming a "failed operation" without further information (not even an error code from the server). The strangest thing is that the sandbox flow was working like a charm until two days ago. Now I am only able to test through the IPN Simulator. What am I doing wrong? -
Selenium And Django - You can use them like in a script?
You can use Django and Selenium like in a script? Example: When user click on a button on web app then in backend selenium go on headless mode to one page url and get page source or click on a button on the url. -
how to render formset initial values in django-tables2?
I would like to render formset with initial values in django-tables2 and allow users to filter it by using django-filter. The problem is that I am not sure how to render initial values and allow users to filter these initial values on their own. If there is no way to connect django-filter, django-tables2 and formset initial values then how can I create a filter that will allow users to filter initial values in my rendered formset. It must allow to select and filter multiple product from the list. The table looks like this: What I am missing is the ability to allow users ability to select number of units and submit it as normal formset so the column # of units should look like this: models.py class ProductComponent(models.Model): related_product = models.ForeignKey(Product, on_delete=models.CASCADE) service = models.CharField(max_length=500, default='', blank=True) component_name = models.CharField(max_length=254, default='') class Request(models.Model): author = models.CharField(max_length=255, blank=True, null=True) related_component = models.ForeignKey(ProductComponent, on_delete=models.CASCADE, blank=True, null=True, default=1) number_of_units = models.IntegerField(default=0) related_product = models.ForeignKey(Product, on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now) filters.py class ProductComponentFilter(FilterSet): related_product = filters.ModelMultipleChoiceFilter( queryset=Product.objects.all(), field_name='related_product', ) class Meta: model = ProductComponent fields = { 'related_product', } views.py def component_list(request): get_components = CostCalculator.objects.all() get_datetime = timezone.now().strftime('%Y-%m-%dT%H:%M:%S') formset = RequestFormset(initial=[{ 'author': request.user.email, 'related_product': component.related_product, … -
Displaying the user's favorite products in Django
Displaying the user's favorite products in Django When I want to display the user's favorite products, the query result does not display anything and returns me None. Actually, I want to show the user which products he has added to his favorite list My model, view and address Url as follows my model: class UserWishlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, related_name='user_favourite') products = models.ManyToManyField(Product, related_name='product_favourite', blank=True, ) my url : path('wish/', views.wish, name='wish'), my view: def wish(request): data = UserWishlist.objects.get(user_id=request.user.id) return render(request, 'home/test.html', {'data': data}) my template : {{ data.products.name }} -
Problem with django rest framework APIview in pythonanywhere
I built an APIView to handle login. I use post method to send email and passwrod like below class LoginApi(views.APIView): permission_classes = (AllowAny,) # Adding permission to everyone def post(self,request): email = request.data['email'] password = request.data['password'] ... This works in my own system but when in push this to pythonanywhere the shape of request.data change like this: in my system : {"email":"email","password":"1234"} but in pythonanywhere is: <QueryDict: {'_content_type': ['application/json'], '_content': ['{"email":"email","password":"1234"}\r\n']}> my django version and rest-framework is the same with pythonanywhere. just my python version is 3.10 but pythonanywhere is 3.9. but I don't think it's the problem. -
Auth0 is showing Callbak URL mismatch error in Django app
I have a Django app that is working fine. I wanted to integrate Auth0's OAuth Authentication to my app. I followed their official tutorial, but when I go to my Login Url, I get the error at Auth0 page that says: Callback URL mismatch Below is the screenshot of error: enter image description here Below is my django project's main urls.py: urlpatterns = [ path("admin/", admin.site.urls, name="admin"), path("", login, name="home_x"), path("accounts/", include("apps.accounts.urls")), # URLs of Login/Registration System ] Below is urls.py of my django app named accounts: urlpatterns = [ path("login", views.login, name="login"), path("logout", views.logout, name="logout"), path("callback", views.callback, name="callback"), path( "switch-workspace/", SwitchWorkspace.as_view(), name="switch_workspace" ), ] Below is my views.py: def login(request): return oauth.auth0.authorize_redirect( request, request.build_absolute_uri(reverse("callback")) ) def callback(request): token = oauth.auth0.authorize_access_token(request) request.session["user"] = token return redirect(request.build_absolute_uri(reverse("switch_workspace"))) def logout(request): request.session.clear() return redirect( f"https://{settings.AUTH0_DOMAIN}/v2/logout?" + urlencode( { "returnTo": request.build_absolute_uri(reverse("login")), "client_id": settings.AUTH0_CLIENT_ID, }, quote_via=quote_plus, ), ) Below is my settings.py: AUTH0_CLIENT_ID=env("AUTH0_CLIENT_ID") AUTH0_CLIENT_SECRET=env("AUTH0_CLIENT_SECRET") AUTH0_DOMAIN=env("AUTH0_DOMAIN") and finally below are my settings in Auth0 Account: Allowed Callbacks URLs: http://127.0.0.1:8000/accounts/switch-workspace/, http://localhost:8000/accounts/switch-workspace/, this is showing in the image below as well: enter image description here Anyone knows that what's wrong? Because I don't think I did anything wrong following the official tutorial here -
Django rest framwork folder structure
i found this question in stackoverflow link. but I still haven't received the answer to my question, what exactly is the standard project structure in Django? -
Can't connect MongoDB with Djongo, Connection timeout error occurs
This is the error raising when I am running the project. raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: ac-yyvwtll-shard-00-00.gcdfin1.mongodb.net:27017: connection closed, ac-yyvwtll-shard-00-01.gcdfin1.mongodb.net:27017: connection closed, ac-yyvwtll-shard-00-02.gcdfin1.mongodb.net:27017: connection closed, Timeout: 30s, Topology Description: <TopologyDescription id: 62f603001b491814aad289bb, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-yyvwtll-shard-00-00.gcdfin1.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-yyvwtll-shard-00-00.gcdfin1.mongodb.net:27017: connection closed')>, <ServerDescription ('ac-yyvwtll-shard-00-01.gcdfin1.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-yyvwtll-shard-00-01.gcdfin1.mongodb.net:27017: connection closed')>, <ServerDescription ('ac-yyvwtll-shard-00-02.gcdfin1.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-yyvwtll-shard-00-02.gcdfin1.mongodb.net:27017: connection closed')>]> -
Python - format datetime with timezone
I have a datetime with timezone field in my model in Django defined like this: created_at = models.DateTimeField(auto_now_add=True) It is stored in database like this: 2022-08-12 09:41:13.815705+02 I have added a property on that model to display custom formatted datetime: @property def created_date(self): date_obj = self.created_at.strftime("%Y-%m-%d %H:%M:%S") return date_obj It is now displayed like this: 2022-08-12 07:41:13 The problem is the two hours time difference between stored time and displayed time. Time is stored in Central European Summer Time (+2). I want the displayed time to display "9:41:13" instead of "7:41:13". It needs to be corrected to users timezone. How can I do this? -
MultiPartParserError: Invalid boundary in multipart: None
I am writing a django and react-native app. I am in the process of making the profile setup page. I tried sending a user-inputed profile image to django but I got "MultiPartParserError: Invalid boundary in multipart: None". here's my code: profile.js- const [ password, setPassword ] = useState("") const [ confpassword, setConfpassword ] = useState("") const [ email, setEmail ] = useState("") const [ gender, setGender ] = useState("") const [ dob, setDob ] = useState("") const [ hobbies, setHobbies ] = useState([]) const [ orgin, setOrgin ] = useState("") const [ lives, setLives ] = useState("") const [ bio, setBio ] = useState("") const [ first, setFirst ] = useState("") const [ last, setLast ] = useState("") const message = props.navigation.getParam("message", null) const [ profileImage, setProfileImage ] = useState(null) const [ val, setVal] = useState(null) const [ op, setOp ] = useState(false) const usern = props.navigation.getParam("user", null) const [ sentI, setSentI ] = useState(null) const sendI = () => { const formData = new FormData() if (profileImage != null){ formData.append( 'image', profileImage,) setSentI(formData) console.log('recieved') } console.log(formData) } const showImagePicker = async () => { // Ask the user for the permission to access the media library const permissionResult = … -
Django move database from one project to another without dataloss
So I used to have my Django Project named "TestProject". Recently I started taking it more serious and renamed it to "ParadoxSite" (the name of the application). Now I am wondering how I can transfer all data stored in db.sqlite3 to this new project without dataloss. Maybe its possible to just run the migration flow, but I couldn't confirm this anywhere so didn't want to run the risk. -
How to pass django values_list to url varialbe using django ORM queryset
I have list of values from django orm query To simplify things, I need to perform this query: id = [1,2,3,4] url = "http://example/"+str(id)+"in/" but here it is return only the last value in list, expected would be check all the list values. -
I want Admin user to change the font, color and theme of a website from Django admin panel?
what is the best way to manage this? Thank You in advance for reaching out and trying to help. -
Using Django using() connections with related fields
I have a Django project that occasionally needs to access (read only) a specific couple of foreign databases. Both databases have identical schemas. I've made an Django app for the database schema. I also set up a database router so that read access will return "unknown" (literally that string), resulting in an "unknown connection." This is intentional so that using(connection) is explicitly required and there is no default. My problem is that once I grab an object from a model, the using() is lost on related objects. Foreign keys fields don't inherit the using(), nor do things like obj.foo_set.all(). Even odder, obj.foo_set.using(...).all() doesn't seem to apply a using(connection) either. It seems like my only solution is to manually resolve any related fields through something like OtherModel.objects.using(obj_id=obj.id)... Is there another way to handle this? I'm having difficulty searching for a solution because using django is a pretty useless search term. I'm reluctant to globally change the managers temporarily. -
Unable to POST data using at Django backend, and Using Javascript For Validation
I'm trying to post numbers, but before I'm validating if the number is filled and the price is empty then focus on the price input, and after filling both submit the form. That's the related form <form method="POST" id="frmAddNumbers" action="{% url 'admin_numberAdd' %}" onsubmit="return validateForm()"> {% csrf_token %} <div class="table-responsive"> <!-- Here range is (1,11) --> {% for i in range %} <table class="table odd"> <tr> <td width="40%"> <label>Add Numbers:</label><br /> <textarea name="number_{{i}}" class="form-control" style="height: 360px"></textarea> </td> </tr> <tr> <td> <label>Price:</label><br /> <input id="price_{{i}}" name="price_{{i}}" type="text" class="form-control" /> </td> </tr> </table> {% endfor %} <table class="table"> <tr> <td> <input type="submit" value="Submit" class="btn btn-primary" /> <input type="submit" value="Submit & Add New" class="btn btn-primary numbersAddNewAdmin" /> </td> </tr> </table> </div> </form> And that's the script with validateForm() function, If I do not use the script then data gets posted as expected. but using script , values didn't get posted. So there is something wrong in the script or with Django there is a certain way to handle that. So need help to fix that. <script> function validateForm() { // Run a loop upto 10 times and then submit the form for (var i = 1; i < 11; i++) { let number … -
How to add a product according to the category in django with custom html template
i want to add products into django db by selecting categories. Its adding the product into db but the category shows its None so. idk views.py def addpro(request): cat = Category.objects.all() if request.method == 'POST': name = request.POST.get('name') price = request.POST.get('price') stock = request.POST.get('stock') cate = request.POST.get('category') img = request.FILES['img'] obj = FileSystemStorage() img2 = obj.save(img.name, img) if Product.objects.filter(name=name).exists(): return redirect('add') else: Product.objects.create(name=name, price=price, stock=stock , image=img2 , categ = cate ) return redirect('add') return render(request, 'Add.html',{'category':cat}) #models.py from django.db import models class Category(models.Model): Name = models.CharField(max_length=30 , null = True) def __str__(self): return str(self.Name) class Product(models.Model): name = models.CharField(max_length=255) price = models.IntegerField(null = True) stock = models.IntegerField(null = True) image = models.ImageField(upload_to='product/',null =True) categ = models.ForeignKey("Category", on_delete=models.CASCADE,null = True) def __str__(self): return self.name -
Field 'id' expected a number but got <category: python >
I am trying to submit a form but the 'category' part of the form is saving. I am creating a notes application, in which a notes form consists of 3 items : Category , Topic and Notes. Category should be unique, if it already exists then add the 'Topic' in the existing Category else create a new category, and then add notes to it respectively. Views.py This is views.py, check here Models.py This is Models.py, check here On page we click, make notes and this redirects us to Notes.html. Notes.html This is notes html file image Home page: Home page image Notes page: Notes page image Error : This is the Error showing Error in topics variable Please help me , what am I missing? Also please guide me a source of learning Django after which I don't make at least these types of mistakes. Thank you in advance. -
admin.site.register doesn´t add my app in admin Django
I´m trying to see the models in the admin. I´ve tried everything but nothing seems to work, could you help me? Note: I´ve also tried with admin.autodiscover() but it didn´t work Here´s what I have in main urls.py: from django.contrib import admin from django.urls import path, include from django.contrib.auth.views import LoginView , logout_then_login urlpatterns = [ path('admin/', admin.site.urls), path('homebanking/', include('Clientes.urls')), in the models.py from my app, I have: class Client(models.Model): customer = models.ForeignKey(TipoCliente, on_delete=models.CASCADE) customer_name = models.TextField() customer_surname = models.TextField() customer_dni = models.TextField(db_column='customer_DNI', unique=True) # Field name made lowercase. dob = models.TextField(blank=True, null=True) branch_id = models.IntegerField() class Meta: db_table = 'client' and my admin.py from my app I have: from django.contrib import admin from Clientes.models import Client # Register your models here. admin.site.register(Client) I really don´t know what´s wrong -
Django admin panel deletion order causing FOREIGN KEY constraint failed
I've been searching and have found many other people that seem to have come upon the same mistake I have, or something similar, however I have been unable to replicate their solutions, or maybe my issue is different, I am unsure. When I attempt to delete a user from the admin panel, I get an error screen saying IntegrityError at /admin/auth/user/ FOREIGN KEY constraint failed, but at no point in the entire page does it mention any model, column, nor anything that could help me narrow it down. I assume it is due to my model which has a models.OneToOneField(AuthUser, on_delete = models.CASCADE), though I would think the on_delete should delete it, it seems to end up dangling or something because if I delete the entry in that table first, and then delete the user that one referenced, they get deleted correctly without issue. I am a beginner to Django, so I'm almost surely misunderstanding something, any help with: understanding what I have to do to make my entries delete themselves correctly upon deleting the user reading the error page correctly to know what's causing it some way to override the admin delete to delete from the other table first … -
How do i populate my database, having a foreign key from swagger UI
I am building an application with django. And i have this user model,dso model... The user model is supposed to have a field that is an instace of Dso model. In essence, there is a relationship between models. Everything is all setup from the codebase, when i try to register a new user with my server gui, i would see the connection there. When i try to register with swaggerUI, i normally would have to make a JSON dictionary input, something like this. { "email": "name@example.com", "username": "example", "password": "example", "name": "example", "address": "My Address", "customerId": "example", **"dso": 4**, "roleId": 2 } From the above, 4 is supposed to be an instance of the DSO table/Model which has the id 4 but then swagger always return an internal server error with error "Cannot assign "4": "User.dso" must be a "Dso" instance." I don't know how to represent a foreignkey relation in JSON. Here is my code base: UserModel: class User(AbstractBaseUser, PermissionsMixin): dso = models.ForeignKey(to=Dso,related_name='dso',null=True,on_delete=models.CASCADE) name = models.CharField(max_length=70) address = models.CharField(max_length=70) roleId = models.IntegerField(default=1) customerId = models.CharField(max_length=70, blank=False, default='') username=models.CharField(max_length=255, unique=True, db_index=True) email=models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_trading = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) @property def … -
How to add img elements with Javascript when using Django?
I am trying to dynamically insert img elements to the website I am building which uses Django for the back-end. The images change often so I pass the src from Python to Javascript like this: views.py path='{% static "../static/assets/'+image_name+'" %}' response = render(request, 'main.html',{'image_path':path}) return response Then I declare a global variable in the template so I can use this in the .js files. main.html var imagePath = {{image_path|safe}} Then I use Javascript to pass this as src to new img elements. However, when I do it, Django cannot find images. When I put the string as src to a img element manually, it works. Does anyone know how to solve this? -
How to change the default username to email, in DRF obtain token login?
This is my login path from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ ... path('login/', obtain_auth_token), ] When I use this as a login, it takes username(though it takes email as field data) & password and generate the token for me { "username": "manig@gmail.com", "password" : "manig@gmail.com" } how I want it { "email": "manig@gmail.com", "password" : "manig@gmail.com" } I want to replace username with email!! how should I modify this ? What I have tried till now is: I have made the custom serializer class AuthTokenSerializer(serializers.ModelSerializer): class Meta: model = AuthUser fields = ('email', 'password') extra_kwargs = {'password': {'write_only': True}} def validate(self, data): user_obj = None email = data.get('email') password = data.get('password') if email and password: user_obj = AuthUser.objects.filter(email=email).first() if not user_obj: raise serializers.ValidationError("This email is not registered") if not user_obj.check_password(password): raise serializers.ValidationError("Incorrect credentials") return data def create(self, validated_data): user = AuthUser.objects.get(email=validated_data['email']) refresh = RefreshToken.for_user(user) return { 'user': user, 'token': str(refresh.access_token) } And here is the view for it class AuthLoginUser(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = AuthTokenSerializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'role': user.role }) And this is how url pattern is urlpatterns …