Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
insert ₹ in python Django mysql. i'm using frontend react and backend Python
Hi There when i was entering ₹ in a textfield i'm getting django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xE2\\x82\\xB9' for column 'sk_ver_reason' at row 1") this textfield is a description box, mysql acception other countries curreny sign but not in indian currency, i have chages much collation from utf8mb... when i hit api this sign failed, but the entry for this api enter in db, same i hit again it run succefully, is it python django error or purely mysql db error. in below image you can see collation of that perticualr field. -
ApplicationOAuth using PyGithub in Django
I am building Github App. I have tried to access repository from Github by using Access tokens, It will work fine Here is the Code username = "user" reponame = "test" g = Github("my_access_token") repo = g.get_repo(username + "/" + reponame) files = repo.get_contents("") But now I want to access the repository by using Application authorizing, for this I am using PyGithub library. Here is the link which demonstrate what i am trying to do exactly. (Must read this..Please) and This is the PyGitHub Docs to achieve above functionality. I am not Getting how to implement this exactly. -
Batch Complete Tasks in DRF
I have my Django website where i can have tasks created and subtasks under tasks i have mark complete option which is working fine i need them to be completed in batch like selecting multiple tasks at once and complete them. serializers.py: class TaskCompleteSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ( 'is_done', ) def update(self, instance, validated_data): person = self.context['request'].user.person task_is_done = validated_data.get('is_done', False) if task_is_done: instance.subtasks.update(is_done=True) instance.is_done = task_is_done instance.done_by.set([person]) instance.save() return instance models.py: class TaskUpdateAPIView(UpdateAPIView): permission_classes = " " serializer_class = TaskCompleteSerializer queryset = Task.objects.all() model = Task lookup_url_kwarg = 'task_id' -
Missing data from template to view
I created a form and am trying to retrieve the data from the view so I can send it to an email. Once I render the page I get a 'keyerror'. I printed the values I am getting from the form and noticed I am not getting the 'phone_number' input. I'm trying to figure where is going the phone_number input Here's my code {% extends "base.html"%} {% load static %} {% block contenido %} <!-- Contact Section--> <section class="page-section" id="contact"> <div class="container"> <!-- Contact Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Contact Section Form--> <div class="row justify-content-center"> <div class="col-lg-8 col-xl-7"> <!-- * * * * * * * * * * * * * * *--> <!-- * * SB Forms Contact Form * *--> <!-- * * * * * * * * * * * * * * *--> <!-- This form is pre-integrated with SB Forms.--> <!-- To make this form functional, sign up at--> <!-- https://startbootstrap.com/solution/contact-forms--> <!-- to get an API token!--> <form id="contactForm" method="post"> {% csrf_token %} <!-- Name input--> <div class="form-floating mb-3"> <input name="full_name" class="form-control" id="full_name" type="text" … -
copy some column from a table to another table
guys I have made two models in Django. first model contains- id (primary key) name age address gender second model contains- id (primary key) name age college class What I am trying to achieve is every time I make entry in first model table it automatically copies name and age field from first model table to second model table. I have tried Foreignkey, OnetoOneField, but could not succeed. I am using Sqlite. -
How to run _icontains method on a foreignkey field in django
I am building a dummy E-commerce site. For this, I wish to build a staff portal where I can search for pending orders by a user's first name. I have made a foreignkey field on my model that I am referencing. But when I use the __icontains method in my views on user field, I get Related Field got invalid lookup: icontains error. I wish to return all orders that have been made by a user that have a certain searched string in their first name. My views.py: class delivery_staff_search_pending_orders(LoginRequiredMixin, generic.View): def get(self, *args, **kwargs): if self.request.user.groups.filter(name='Delivery_staff_admin').exists(): search_query = self.request.GET['query'] filter_form = PendingOrdersFilterForm() orders = Order.objects.filter(preproccessed=True, ordered=True, delivered=False) searched_pending_orders = orders.filter(user__icontains=search_query) context = { "filter_form": filter_form, "pending_orders_list": searched_pending_orders } return render(self.request, "staff/delivery/pending_orders.html", context) My Order model: user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) ref_code = models.CharField(max_length=20, default=1234) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey("BillingAddress", on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey("Coupon", on_delete=models.SET_NULL, blank=True, null=True) preproccessed = models.BooleanField(default=False) dispatched = models.BooleanField(default=False) delivered = models.BooleanField(default=False) Refund_requested = models.BooleanField(default=False) Refund_granted = models.BooleanField(default=False) Paid_price = models.FloatField(default=0) The user model is the standard django.contrib.auth.models user model -
Django-Filter: Method argument to filter two attributes
I created a model with a way to grant a credit with some attributes like customer id, amount of credit, result of the credit, due date, created date. for the purpose of the app, I should filter the credit's period of the validity. Then I create a method in the filter like this: period_of_validity = filters.BooleanFilter( method="period_of_validity_filter", help_text="Get the period of validity of the credit according to the remaining days to the due date", ) and the method is: def period_of_validity_filter(self, queryset, name, value): result = queryset.filter( Q(result=CreditResult.GRANTED) | Q(due_date__gt=datetime.date.today())) return result However, I am not sure if the two Q are correct in order to find the granted credits and the credits with a due date greater than equal today. I give thanks for your help. -
Access local vagrant VM through a Django app running locally
Context: I am playing around with Django and Vagrant and I would like to see if I can have them interact with each other where a Django app running locally can access a local Vagrant VM. I have a Django app that I'm running locally using python manage.py runserver and I have a Vagrant VM that is up and running somewhere on my local machine in path/to/local/vagrant/vm. I would like to ssh and/or execute commands on the aforementioned local Vagrant VM through the Django app. Is that such thing possible? If so, how? If not, then how can I achieve something similar where I can have a Django app interact with a local VM. -
Is it possible to have a OneToOneField in Django that's only null=True in one direction?
Is it possible to create a OneToOneField in Django that is only null=True in one direction? Ex: class Building(models.Model): ... class Roof(models.Model): building = models.OneToOneField(...) ... A building doesn't technically need to have a roof. Plenty of unfinished buildings don't have them. But you can't have a roof without a building. Also, a building can only have one roof, and a roof can only be on one building, hence OneToOneField. -
Why is my Django data migration from ForeignKey field to OneToOneField not working?
I have some models with a ForeignKey field that points to another model: class Specimen(models.Model): ... class ResultA(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) ... class ResultB(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) ... At some point, I realized that each specimen will only ever have zero or one of each type of result, so it probably makes sense to turn that into a OneToOneField. The plan is to: Create an additional specimen_new field that's a OneToOneField on each result Create a data migration that will move the data from the ForeignKey field to the OneToOneField field Delete the ForeignKey field Rename the new specimen_new OneToOneField to just specimen Update all the code references to use the new OneToOneField properly Step 1 was pretty simple: class Specimen(models.Model): ... class ResultA(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) specimen_new = models.OneToOneField(Specimen, on_delete=models.CASCADE, ...) ... class ResultB(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) specimen_new = models.OneToOneField(Specimen, on_delete=models.CASCADE, ...) ... I'm stuck on step 2 - creating the data migration. Right now, it looks like this: from django.db import migrations def migrate_results(apps, schema_editor): # Get the model Specimen = apps.get_model('ahs', 'Specimen') # Update every specimen for specimen in Specimen.objects.filter(): for field in Specimen._meta.get_fields(): # Look for fields that … -
How to setup nginx to site to a Django app over https?
I have an application that I am running with multiple docker containers with a docker-compose file. Two main containers are django_container and nginx_container. I want to force using https for my application but unfortunately, my Nginx config doesn't seem to work. Basically, my gunicorn server seems to be running OK. I can see the http://django:8001 from inside the nginx_container, but I can't see http://example.com from inside it or outside. Here is the content of my Nginx config server { listen 80; server_name example.com; rewrite ^ https://example.com$request_uri? permanent; } server { listen 443 ssl; server_name example.com; ssl_certificate /etc/nginx/certs/example_com.crt; ssl_certificate_key /etc/nginx/certs/cert.key; access_log /log/nginx.access.log main; location / { proxy_pass http://django:8001; proxy_set_header X-Forwarded-Proto $scheme; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } What am I missing here? Thanks a ton! -
Django rest framework not refreshing template changes
I was trying to update my django rest framework browsable api template, initially trying to change the theme and afterwards changing the navbar branding text, but, after creating the rest_framework/api.html file for the first time, the changes got stuck and the initial changes will not either update nor delete. I've tried deleting the whole proj/app/templates/rest_framework directory, but the changes are still there. I also deleted my browser's cache and cloudflare's cache, restarted Apache 2, and even restarted the server. This is my app directory: website ├── __init__.py ├── admin.py ├── apps.py ├── locale │ └── (more folders) ├── models.py ├── static │ └── (more folders) ├── templates │ ├── anime │ │ ├── detail.html │ │ └── index.html │ ├── (here was the rest_framework directory with the api.html file) │ ├── footer.html │ ├── imports.html │ ├── navbar.html │ └── website │ ├── index.html │ └── welcome.html ├── tests.py ├── urls.py └── views.py My old api.html (the last version before editing) looked like this: {% extends "rest_framework/base.html" %} {% load i18n %} {% block bootstrap_theme %} <link rel="stylesheet" href="https://example.com/static/bootstrap/bootstrap.css" type="text/css"> {% endblock %} {% block branding %} <a class="navbar-brand" rel="nofollow" href="#"> My Project </a> {% endblock %} In the browsable … -
I am getting "Could not parse the remainder: '=="dashboard"' from 'section=="dashboard" error what could be the possible reason for this error?
this is my base.html. I tried replacing == with = .Also, I properly checked if I forgot closing tag but didn't found such problems -
Django Page loading error ?page=undefined
learning pagination and not understanding why page variable is undefined. I can hover over each page object and tool tip shows correct page=page#, each button is numbered correctly as well. This is the function from the view of the app: def projects(request): projects, search_query = searchProjects(request) results = 4 page_number = request.GET.get('page') if page_number == None: page_number = 1 paginator = Paginator(projects, results) try: projects = paginator.page(page_number) except PageNotAnInteger: page_number = 1 projects = paginator.page(page_number) context = { 'projects': projects, 'search_query': search_query, 'paginator': paginator } return render(request, 'projects/projects.html', context) The html code for pagination is as follows: <div class="pagination"> <ul class="container"> {% for page in paginator.page_range %} {% if page == paginator.number %} <li><a href="?page={{page}}" class="btn page-link btn--sub" >{{page}}</a></li> {% else %} <li><a href="?page={{page}}" class="btn page-link">{{page}}</a></li> {% endif %} {% endfor %} </ul> </div> when a page is clicked, the page does not refresh to the correct page or show the current page highlighted, the initial content(1st page) is displayed. When I print the values of the paginator attributes I can see the correct pages generated and objects referenced correctly. Just not understanding why the anchor {{page}} references are not being returned to the view on a GET event. This … -
How to fix the encode error in Django while trying to send an e-mail
Im trying to send an verification e-mail to a new registrated account in Django, but im getting an encode error that I dont know how to fix, please help me to fix it, so then I can succeffuly verify the account aaaaaaaaaaaaaa if DEBUG: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'jamelaumn@gmail.com' EMAIL_HOST_PASSWORD = xxxxx # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' my urls.py: path('register/', views.account_register, name='register'), my views.py: from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.core.mail import EmailMessage from django.conf import settings from django.template.loader import render_to_string def account_register(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' current_site = get_current_site(request) message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) email_body = message email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to]) email.send() return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active … -
Querying django models to include and exclude items
I currently have 2 models as such class Recipe(models.Model): account = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True) name = models.TextField(null=True, blank=True) slug = models.SlugField(null=False, blank=True, unique=True) image_path = models.ImageField(upload_to=MEDIA_URL, null=True, blank=True) description = models.TextField(null=True, blank=True) date_added = models.DateField(auto_now_add=True) class RecipeIngredients(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) ingredient = models.TextField(null=True, blank=True) quantity = models.CharField(max_length=10, null=True, blank=True) type = models.CharField(max_length=50, null=True, blank=True) I am trying to do a query where if I have a list of say 2 or more items, say ingredients = ["egg", "bacon", "rice"] That it returns to me only the recipes that have exactly egg, bacon, and rice, or less. I was able to do this in a hacky way, but it is really slow and not using the ORM correctly I feel. for i in ingredients: r = RecipeIngredients.objects.filter(ingredient__icontains=i) results.append(r) for result in results: for r in result: recipes.append(r.recipe) for r in recipes: recipeingredients = r.recipeingredients_set.all() for ri in recipeingredients: ingredient = ri.ingredient if ingredient not in ingredients: try: recipes.remove(r) except: print(r) print("end of recipe") Any help on how to make this a more correct query would be appreciated. -
How can i submit initial data in database while migrating in Django?
Info: I want to save the auth-group records while migrating the database in Django. the records which come from auth_groups.json. Maybe my question is similar with others but i don't understand the logic with auth_groups.json. I have multi tenant database but when i create a new tenant i want to be save with init. 0003_auto_20220525_2056.py # Generated by Django 4.0.4 on 2022-05-25 20:56 from django.db import migrations from django.core import serializers fixture_filename = 'fixtures/groups.json' def load_initial_data(apps, schema_editor): fixture = open(fixture_filename, 'rb') auth_group = apps.get_model('auth', 'Group') for obj in auth_group: obj.save() fixture.close() class Migration(migrations.Migration): dependencies = [ ('account', '0002_initial'), ] operations = [ migrations.RunPython(load_initial_data), ] auth_groups.json [ { "model": "auth.group", "pk": 1, "fields": { "name": "admin", "permissions": [] } }, { "model": "auth.group", "pk": 2, "fields": { "name": "producer", "permissions": [] } } ] -
django. The manage.py is not working after migrating mysql table
I install mysql as my database in my django project. I did makemigration and migrate it on the django. After that I wanted to try to run the server, but the python manage.py is not working at all even if there is python stored in my computer. python_version_in_cmd I have the screenshot here where it shows no response at all but pip is responding. django This is my computer environment path computer enviroment path When I was installing mysql the mysql/python was failing, is that the problem? any hints? -
Cannot resolve keyword 'slug' into field. Choices are: id, location, profile_image, stories, twitter, user, user_id, website
I'm trying to create profile page for a user when I click on create profile instead of showing me the edit template that will allowed me to edit all these fields then it throws me an error like this: Cannot resolve keyword 'slug' into field. Choices are: id, location, profile_image, stories, twitter, user, user_id, website i want a user to be able to create profile. How can i solve this problem ? the urls: path('editprofile/<slug:slug>/edit', views.EditProfileView.as_view(), name='editProfile'), the models: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_image = models.ImageField(upload_to="avatars/") stories = models.TextField(max_length=500,blank=True, null=True) website = models.URLField(max_length=250, blank=True, null=True) twitter = models.URLField(max_length=250, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) the views: @login_required(login_url='login') def profile(request, pk): profiles = Profile.objects.filter(user=request.user) questions = Question.objects.filter(user=request.user) context = {'questions':questions, 'profiles':profiles} return render(request, 'profile.html', context) class EditProfileView(UpdateView): model = Profile fields = ['profile_image', 'stories', 'website', 'twitter', 'location'] template_name = 'edit_profile.html' success_url = reverse_lazy('index') the profile template: <div class="container"> <div class="row"> <a href="{% url 'editProfile' user.id %}" class="btn btn-primary">Create Profile</a> </div> </div> -
Get src of image file stored in dtabase?
I have a dessert model in django with a property called picture: class Dessert(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=1000, blank=True) picture = models.ImageField(upload_to ='uploads/desserts-pics/', max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(1)]) tags = models.ManyToManyField(Tag, related_name="desserts") def __str__(self): return self.name + " ($" + str(self.price) +")" And i want to show the image in my front with react, like this: <img src={dessert.picture}> dessert is an instance of the Dessert model witch i got from a request, but the picture is a file not an image, how the hell do i get the src? sorry, i know it's a silly question but i didn't find the answer anywhere else. -
Access to fetch at **link** from origin 'http://localhost:3000' has been blocked by CORS policy
I'm trying to exchange the authorization code for an access token for a Google Calendar integration. I was following Using OAuth 2.0 for Web Server Applications. The examples shown there were for Flask, but I'm using Django. The problem is, I can't redirect to authorization_url because it says Access to fetch at link from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. @api_view(['GET']) def authorize(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = 'http://localhost:3000/' authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') response = redirect(authorization_url) return response However in my settings.py I have: CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000",] -
Getting a list index out of range and i'm not sure why
I get a index list out of range error and cant figure out why. The error seems to be occurring at the line p2 = 'FLipkart Price: $' + price2[0].text. For some reason the similar code that pertains to the the variable p works fine but not this one. If it helps, I am just trying to make a website that compares prices at amazon and flipkit. I am using python and the Django framework. def search_item(request): item = '' if request.method == 'POST': item = request.POST.get('textfield') wbd = wb.Chrome('/usr/bin/chromedriver') #webdriver_path = '/usr/bin/chromedriver' amazon_url = 'https://www.amazon.com/' flip_url = 'https://www.flipkart.com/' search_url = amazon_url + ("s?k=%s" % (item)) print(search_url) wbd.get(search_url) price = wbd.find_elements_by_class_name('a-price-whole') p = 'Amazon Price: $' + price[0].text l = 'Link: ' + search_url search_url2 = flip_url + ("search?q=%s" % (item)) print(search_url2) wbd.get(search_url2) price2 = wbd.find_elements_by_class_name('_1vC4OE') p2 = 'FLipkart Price: $' + price2[0].text l2 = "Flipkart Link: " + search_url2 return render(request, 'index.html', {'aprice': p, 'alink': l, 'fprice': p2, 'flink': l2}) -
Trying to get access token with django-oauth-toolkit using fetch not working while working using jquery
I'm trying to call endpoint to generate access token using oauth in django it is working when I call the endpoint using jquery but not working when I try to call it with fetch here is the code for fetch fetch(`https://<domain>/o/token/`, { method: 'POST', body:{ grant_type:'password', client_id: "<client-id>", client_secret:"<client-secret>", username:"<username>", password:"<password>" } }) .then(res => res.json()) .then(res => {console.log(res)}); the output is {error: 'unsupported_grant_type'} while when I'm calling it using jquery ajax as below its working $.post({ url:'https://<domain>/o/token/', data:{ grant_type:'password', client_id: "<client-id>", client_secret:"<client-secret>", username:"<username>", password:"<password>" }, success: function(data){ console.log(data); } }) the output is {access_token: '<access-token>', expires_in: 3600, token_type: 'Bearer', scope: 'read write groups', refresh_token: '<refresh-token>'} -
Why is Factory Boy populating Local DB instead of Test DB
I set up ~100 unit test for a django app, and later realized each unit test run was creating test users in my local database, instead of the test database. I found a "solution", but I don't know why it's working. Maybe someone can help. apps/user/tests/factories.py class CompanyFactory(factory.django.DjangoModelFactory): class Meta: model = Company title = fake.name() class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User auth0_id = fake.random_number() email = "unit_test_user@cart.com" company = SubFactory(CompanyFactory) When running a test that uses the factory like this, fake users are being persisted in the DB: When changing the UserFactor inheritance to factory.Factory instead of factory.django.DjangoModelFactory it works fine. Anyone know why this behavior is happening? -
Django Cant query Oracle
I have a Django application, and it works fine. So far, the connection to Oracle seems to be ok. The problems is when I try to query data. I use the objects property and it gives me "ORA-00933: SQL command not properly ended" error. So far I ven looking the query and I think is the problem. Anyway, I try that same query on oracle and sems to be pk print(CONTRIBUYENTES.objects.using('VIALISDB').all().query) SELECT "FGESILDOWN.SILD_DET_CONTRIBUYENTES"."DTCO_FOLIOSOLICITUD" FROM "FGESILDOWN.SILD_DET_CONTRIBUYENTES" Does someone knows the problem?