Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set Vue.js language base on Django LANGUAGE_CODE
I had a Django project where i use Vue.js for some parts. I've translated all django parts and i now how to translate all Vue.js parts. Language switcher is on Django template page and it's changing language in all django project and apps respectively. I need to get current Django LANGUAGE_CODE and use it for setting Vue.js language. This is a short version of app.js (somehow a point of entry for my Vue.js) where i import translations.json with a translations and setting Vue.js language import Vue from 'vue'; import VModal from 'vue-js-modal'; import GetTextPlugin from 'vue-gettext'; import translations from '../../locale/translations'; const settings = { apiKey: '', lang: 'ru_RU', coordorder: 'latlong', version: '2.1', }; Vue.use(GetTextPlugin, { availableLanguages: { en_US: 'American English', ru_RU: 'Russian', }, defaultLanguage: 'ru_RU', translations, }); If i change field defaultLanguage: 'LANGUAGE' in GetTextPlugin it will change the language for Vue.js. So i need to know how to get Django current language to set it here. -
Django send request to API, where URL is Dynamic
How the URL looks like http://<IP_ADDR>:<PORT>/api/post/<POST_NUMBER> Here the POST_NUMBER is dynamic, how to send a request to the Page like this http://127.0.0.1:8080/api/post/14 Where 14 is the post number Here is my URL Pattern path('api/post/<int>', views.PostView, name="Post") Here is the PostView def PostView(request,POST_NUMBER = 0): print(POST_NUMBER) My error is PostView() got an unexpected keyword 'int' -
How to write test for graphene graphql in django
Please can anyone help in testing graphene and graphql with django I tried using built-in django test but it didn't see my file I used pytest but it complaining of ModuleNotFoundError when importing my schema I will like someone to show me a course on advanced python class Query(ObjectType): calculate_price = Float(margin=Float(), exchangeRate=String( ), saleType=Argument(SaleType, required=True)) def resolve_calculate_price(self, info, **kwargs): margin = kwargs.get('margin') exchangeRate = kwargs.get('exchangeRate') saleType = kwargs.get('saleType') request_from_coindesk = requests.get( url='https://api.coindesk.com/v1/bpi/currentprice.json') json_result_from_coindesk = json.dumps(request_from_coindesk.text) coindesk_result = json.loads(json_result_from_coindesk) result = json.loads(coindesk_result) rate_to_calculate = result["bpi"]["USD"]["rate_float"] if saleType == SaleType.sell: calculated_value = (margin/100) * rate_to_calculate new_rate = (rate_to_calculate - calculated_value) * 360 print(18, new_rate) return new_rate elif saleType == SaleType.buy: calculated_value = (margin/100) * rate_to_calculate new_rate = (rate_to_calculate - calculated_value) * 360 print(19, new_rate) return new_rate else: raise GraphQLError('please saleType can either be buy or sell') #my test file from graphene.test import Client from buy_coins.schema import schema def test_hey(): client = Client(schema) executed = client.execute('''calculatePrice(margin, exchangeRate, saleType)''', context={ 'margin': '1.2', 'exchangeRate': 'USD', 'saleType': 'sell'}) assert executed == { "data": { "calculatePrice": 3624484.7302560005 } } I want to be able to test all possible cases. I want to understand the module import issue I want someone to refer an advanced python course -
Saving temporary images to static directory or not in django
I'm doing a project where i create some images using seaborn and then i display them to the user. Since the images will last only a couple of hours it's a good way to save them into the static directory or should I behave differently? If so what should I do? -
How to use Django-hitcount package to build a view count
Am learning Django and came across this Django package called 'Django-hitcount'. But I don't know how to use it in my count. I want to display the number of times that an object is viewed Below is my views.py def home(request): songs = Songs.objects.all() return render(request, 'explore/home.html', {'songs': songs}) count_hit = True This next is my model.py class Songs(models.Model, HitCountMixin): ... plays = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') updated = models.DateTimeField(auto_now=True, auto_now_add=False) class Meta: ordering = ['-updated'] def __str__(self): return self.song_title And my html file ... {{ song.song_title }} {{ song.artist }} plays: {% get_hit_count for [song] %} -
how to get absolute url of a model from another model in django
how to get absolute object of a model from another model depend on its ID models.y class Order(models.Model): ... id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') ... class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE , null=True) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) ... def get_absolute_url(): return reverse('print' , kwargs={'id':ordering.id}) views.py class ProductDetailView(LoginRequiredMixin , DetailView): model = Order template_name = 'order/print.html' queryset = Order.objects.all() context_object_name = 'product' def get_object(self): id_ = self.kwargs.get('id') return get_object_or_404(Order , id=id_) it it possible to get the absolute url when create a new post? id of Order model ! -
How can I add a form when customers place a order(make a reservation) in Django, Python
I want to add a form it's input from customers when they place an order. Where do I have to place a form? Would someone suggests to me about all the files that I have to change and an example of code? I use for this part app of reservation, order and servise in Django. This is my models.py in reservation app. from django.db import models from service.models import Nursery class Reservation(models.Model): reservation_id = models.CharField(max_length=250, blank=True) date_added = models.DateField(auto_now_add=True) class Meta: db_table = 'Reservation' ordering = ['date_added'] def __str__(self): return self.reservation_id class ReservationItem(models.Model): nursery = models.ForeignKey(Nursery, on_delete=models.CASCADE) reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE) quantity = models.IntegerField() active = models.BooleanField(default=True) class Meta: db_table = 'ReservationItem' def sub_total(self): return self.nursery.price * self.quantity def __str__(self): return self.nursery This is my views.py of reservation app. from django.shortcuts import render, redirect, get_object_or_404 from service.models import Nursery from .models import Reservation, ReservationItem from django.core.exceptions import ObjectDoesNotExist import stripe from django.conf import settings from order.models import Order, OrderItem from django.template.loader import get_template from django.core.mail import EmailMessage def _reservation_id(request): reservation = request.session.session_key if not reservation: reservation = request.session.create() return reservation def add_reservation(request, nursery_id): nursery = Nursery.objects.get(id=nursery_id) try: reservation = Reservation.objects.get(reservation_id=_reservation_id(request)) except Reservation.DoesNotExist: reservation = Reservation.objects.create( reservation_id = _reservation_id(request) ) reservation.save() … -
Celery with Redis and Django giving WorkerLostError on long running tasks
I have a long running Celery task that computes the PDP of a feature. Below is the shared task that's run: @shared_task def get_pdp_single(bst, train_df, feature, value, f_id=-1): x_temp = train_df.copy() x_temp.iloc[:, f_id] = value data = xgb.DMatrix(x_temp, feature_names=x_temp.columns.tolist()) predictions = (model.predict(data)) avg_predictions = np.mean(predictions) result_dict = { "feature": feature, "avg_predictions": avg_predictions.item() } return result_dict I'm computing Hstatistics of all the features taken in the XGBoost model built. So, we have lots of such tasks being queued in the Broker (Redis). ~12k tasks gets queued into Redis for this. I have a 8core 16GB VM on which I instantiate a single Celery worker to do this task. Each single child task takes ~40 seconds to complete, this is because XGBoost predict method takes its time to complete. On such long running task, I'm invariably getting WorkerLostErrors and it is quite unpredictable when and how this is occurring. However, I'm pretty sure this is because of the number of tasks being queued on the broker, because ~4-5k tasks run fine on the same setup without any issues. Below is the stack trace that I get on Celery. Restarting celery worker (/~/anaconda3/envs/py35_clone_canary/bin/celery -A ba_tpe_python_service worker -Q staging_celery_queue --loglevel=info) Traceback (most recent call … -
Django Renaming/refactoring a custom user model
I have a custom user model: class CustomUser(AbstractUser): already migrated and populated with some records. I want to rename this CustomUser to MyUserModel. In Pycharm I right-clicked on the name and chose refactor - rename so every reference to this model is also renamed. I then ran python3 manage.py makemigrations which gave me the below error: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL So I went to myproject.settings and changed the AUTH_USER_MODEL to MyUserModel. The makemigrations then worked. and when I looked into the migration file it looked like this: class Migration(migrations.Migration): dependencies = [ ('auth', '0011_update_proxy_permissions'), ('users', '0002_auto_20190916_0658'), ] operations = [ migrations.CreateModel( name='MyUserModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated … -
user auth is_active false flag not working in Django
I am using is_active flag is equal to false in views.py so non-superusers can log in also but that is not working. Only superuser is able to log in. Here are some codes Login logic view: def logingin(request): if request.method == 'POST': username = request.POST.get('username','') password = request.POST.get('password','') user = auth.authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: return redirect('/signup') return render(request, 'login.html') signup logic view def signup(request): if request.method == 'POST': user_name = request.POST.get('user_name','') first_name = request.POST.get('first_name','') last_name = request.POST.get('last_name','') email = request.POST.get('email','') password = request.POST.get('password','') if User.objects.filter(email=email).exists(): messages.error(request, 'E-Mail Already Exist Please Use Different Email') else: user = User.objects.create_user(user_name, email, password) user.is_active = False user.first_name = first_name user.last_name = last_name user.save() return render(request, 'signup.html') I expect that all user can log in through -
Warned current user about for logging out the account
How can I warned the User that his/her account needs to be logged out because it logged in in other sessions The code for preventing multiple session in django is in this http://www.jiajianhudong.com/question/1991002.html -
how to retrieve data from MS SQL using wildcard with LIKE
I have a django project that is connected to MS SQL using pyodbc. I am able to connect and retrieve data. But the problem is when i tried to filter the data on multiple fields using WHERE & LIKE the system crash crash and display the below error. 'tuple' object has no attribute 'format' views.py from django.shortcuts import render import pyodbc def connect(request): conn = pyodbc.connect( 'Driver={ODBC Driver 17 for SQL Server};' 'Server=DESKTOP-LPD1575\\SQLEXPRESS;' 'Database=testDB;' 'UID=test;' 'PWD=test;' ) query = 'n' queryid = 3 cursor = conn.cursor() c = cursor.execute('SELECT * FROM Artist where artistName like ? or id = ?',('%{0}%','{1}').format(query,queryid)) print(c) return render (request,'connect.html',{"c":c}) connect.html <table align = "center"> <tr align="center"> <th>id</th> <th>FolderNumber</th> <th>Folderdate</th> </tr> {% for row in c %} <tr align="center"> <td>{{ row.0 }}</td> <td>{{ row.1 }}</td> <td>{{ row.2 }}</td> </tr> {% endfor %} </table> -
Django Display first item from related_name list
I'm working on a project using Python(3.7) and Django(2.2) in which I have implemented two models ItemModel and Images so every item will have multiple images and added item into the images model and add a related_name but when I try to access these images in Django template it's not providing any information regarding those images. Here are my models: From models.py: class ItemModel(models.Model): stock_number = models.IntegerField(blank=False) title = models.CharField(max_length=255, blank=False) price = models.IntegerField(blank=False) description = models.TextField(max_length=1000) condition = models.CharField(max_length=255, choices=COND_CHOICES, blank=False) model = models.CharField(max_length=255) dimensions = models.CharField(max_length=255) make = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Images(models.Model): item = models.ForeignKey(ItemModel, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to=images_directory_path) And here's I'm trying to access these images for an item in the template: {% for img in item.images.all %} {% if forloop.first %} {{ item.images.first.name }} {% endif %} {% endfor %} what can be wrong here? -
Create get_full_name in django on from foreign model
I have two model called User and Userprofile like below. I want to render display user full_name associated with its own post in django templates. Currently It is only displaying user email instead of user full name in the templates. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(_("Username"), max_length=50, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] objects = CustomUserManager() def __str__(self): return self.email def get_full_name(self): return self.email And another model is here class UserProfile(models.Model): user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE) first_name = models.CharField(_("First name"), max_length=50) middle_name = models.CharField(_("Middle name"), max_length=50, blank=True, null=True) last_name = models.CharField(_("Last name"), max_length=50) class Meta: verbose_name = _("User profile") verbose_name_plural = _("User profiles") def __str__(self): return self.first_name + " " + self.middle_name + " " + self.last_name def get_full_name(self): return ' '.join([name for name in [ self.first_name, self.middle_name, self.last_name ] if name]) def get_absolute_url(self): return reverse("userprofile_detail", kwargs={"pk": self.pk}) How can I render user full_name instead of user email or username in the templates. -
Migration does not work after restore backup DB in django
i'm trying to transfer DB of production server on my test server. now i have a success backup and restoring database and i can see data on admin page as well. but when i running python manage.py migrate migration not working and django tell me No migrations to apply. but I KNOW there is migartion that not applied on this DATABASE yet. also when i go to specific model from django admin page 500 server error appear <some_field> field is not exist . when running python manage.py showmigration it's showing me all migration done .as information i'm running django by uWSGI and postgresql and nginx.(i can see a migration in ./manage.py showmigartion list that isn't apply on new database yet but django show me y done migration. and i do this process exactly same way in my local and all going well but on the server test this problem appear). thank you. -
how to add options in select field dynamically in django?
this is my model file class Add_category(models.Model): Category = models.CharField(max_length=100) Image = models.ImageField() MetaKeyword = models.CharField(max_length=100) MetaDesc = models.CharField(max_length=100) def __str__(self): return self.Category In this i have tried to add city field and choices must come in this field by the help of Add_category model but it fails. class Make_Invoice(models.Model): Order_no = models.IntegerField() Invoice_no = models.IntegerField() Product_name = models.CharField(max_length=100) Product_Id = models.IntegerField() Quantity = models.IntegerField() City = models.CharField(max_length=100, choices = Add_category.Category, default='Select') PLEASE HELP -
I'm going through a django tutorial but currently stucked in an error i.e.. "Page Not Found" on admin page
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in just.urls, Django tried these URL patterns, in this order: admin/ shop/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is my code: Main ecom\urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shop.urls')) ] Now shop\urls.py: from django.urls import path from . import views urlpatterns = [ path("",views.index, name="ShopHome") ] And shop\views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Shop Index") -
Cannot delete some instances of model because of FK
Python 3.6 and Django 1.11.7. I've got two Models look like the following: class User(): name = models.CharField() ... class UserInfo(): user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True, related_name='info') I wanted to delete some user instance A, and I explicitly deleted user A's info. But when I tried to delete the user model user.delete(), I got the ProtecedError: ProtectedError: ("Cannot delete some instances of model 'User' because they are referenced through a protected foreign key: 'UserInfo.user'", <QuerySet [<UserInfo: UserInfo object>]>) Then I tried to put the delete inside a try/catch looks like follows: try: user.delete() except ProtectedError: UserInfo.objects.filter(user=user).delete() user.delete() But still got the same exception. What might went wrong in my operation? -
django-hvad and modelform_factory()?
Trying to create a form with name booking status as admin user, by using the django-hvad module somehow I'm getting this error as below? Any help will be appreciated. Versions: python 3.6 django 2.2.4 django-hvad 1.8.0 OS:windows settings.py INSTALLED_APPS = [ 'booking', 'booking.tests.test_app', 'hvad' ] models.py from hvad.models import TranslatedFields, TranslatableModel class BookingStatus(TranslationModelMixin, TranslatableModel): """ Master data containing all booking status. For translatable fields check ``BookingStatusTranslation``. :slug: A unique slug identifier. translated: :name: The displayable name for the status. """ slug = models.SlugField( verbose_name=_('Slug', unique=True), ) translations = TranslatedFields( name=models.CharField( max_length=128, verbose_name=_('Name'), ) ) Error TypeError at /admin/booking/bookingstatus/add/ TypeError: modelform_factory() got an unexpected keyword argument 'change' -
How can I change Model values from within Django Admin's response_change?
I have added a custom button to my Django Admin by overriding change_form.html. I'd like this button to read a site_url field from the model itself, and then programatically change the model's form fields (without saving the model).. so it can reviewed and corrected before saving. I have successfully got my button to print the object by overriding response_change. I can also pre-populate the template by using extra_context by overriding change_view. def response_change(self, request, obj): if '_scrape-site' in request.POST: print(obj) return HttpResponseRedirect(".") return super().response_change(request, obj) I'd like to be able to enter a site_url and scrape it using requests/bs4 or scrapy, and then return those values into the change_form in the Title and Summary text boxes (see https://imgur.com/dttzPIt.jpg). Is that possible? -
ModuleNotFoundError: No module named 'django_project.users'
As the title says. I have been through multiple threads of StackOverflow with similar questions as to mine and none of them have given me a working solution. My directories: -
int() argument must be a string, a bytes-like object or a number, not 'MaterialRequest'
I am trying to access form data in a queryset and it throws the following error: int() argument must be a string, a bytes-like object or a number, not 'MaterialRequest' Views.py s_o = form.cleaned_data['sales_order'] MaterialRequest.objects.filter(id=s_o).update(is_allocated = True) in the print statement it says that s_o is 1, but I can't equate it with the id in query? What is it that I am doing wrong and how can I change that? -
How can I add a new field from the other app's models.py to html in Django, Python
I want to change the field. I have email.html of reservation app and order_detail.html of order app. Both files have a word Nursery information: at the bottom of the page. I want to use a field of nursery from service app under the words Nursery information of both html files. I wrote order.nursery but it didn't show up. The other like order.shippingAddress1 could show up. How can I show up order.nursery like any others? My relational app names are reservation, order, service. This is email.html of templates of reservation app. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>New Reservation #{{ transaction.id }} - TS</title> <style> table { width: 60%; margin: 0 auto; border-collapse: collapse; } table tr td { border: 1px solid #c1c1c1; } p { padding-right: 50px; padding-left: 50px; } </style> </head> <body> <center> <h1>Thanks for reserve with us</h1> <p>This email is to confirm that you have reserved on the TS.<br>Please make sure that all the details of your order are correct.</p> </center> <br> <table> <tr> <td valign="top" colspan="2" style="width: 50%;"> <b>Your Address:</b><br> {{ transaction.billingName }}<br> {{ transaction.billingAddress1 }}<br> {{ transaction.billingCity }}<br> {{ transaction.billingPostcode }}<br> {{ transaction.billingCountry }}<br> </td> <td valign="top" colspan="2" style="width: 50%;"> <b>Reservation: … -
How to search the grade level and payment-type per grade level and subject using two select option?
\\html <form method="post" action="/newEnroll/"> {% csrf_token %} <table> <tr> <td></td> <td> <input type=submit value="submit" id="enroll" class="enroll" formaction="/newEnroll/"> </td> <td> <input type='button' name='back' value='Back' class='button' onclick="history.back()" /> </td> </tr> </table> <form action="" method="get"> {% csrf_token %} <select name="gradelevel" id="gradelevel"> <option value="0">-- EducationLevel --</option> {% for ylvl in edulevel %} <option value="{{ylvl.id}}" name="gradelevel" >{{ylvl.Description}}</option> {% endfor %} </select> <select name="paymentID" id="paymentID" required="required"> <option name="NULL" value="0" >----Payment Type----</option> {% for pay in payment %} <option name="paymentID" value="{{pay.id}}" >{{pay.Description}}</option> {% endfor %} </select> <input type="submit" value="View" onchange="showResult(this.value)" id="showTxt" formaction=""> </form> <div id="paymentshow"> <tr><th>Subject</th></tr> <tr> </tr> {% for sub in subj %} <tr> <td>{{sub.Description}}</td> </tr> {% endfor %} <tr><th>Payment Type</th></tr> {% for schedule in sched %} <tr> <td>{{schedule.Remark}}</td> <td>Php {{ schedule.Amount|floatformat:2}}</td> </tr> {% endfor %} </form> </form> </body> <script> function showResult(subj) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("POST", "{% url 'enrollmentform' %}?gradelevel="+subj, true); xhttp.send(); } </script> <script> function payment(str) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("paymentshow").innerHTML = this.responseText; } }; xhttp.open("POST", "{% url 'searchpayment' %}?payment="+str, true); xhttp.send(); } </script> \\views paymentID = request.POST.get('paymentID') sched … -
The non-superusers are not able to log in in Django
I've created a view for login but Django only authenticates the superuser. The non-superusers are not able to log in. def logingin(request): if request.method == 'POST': username = request.POST.get('username','') password = request.POST.get('password','') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: return redirect('/signup') return render(request, 'login.html')