Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show a specific content to specific user in Django
I'm a beginner at Django, I am building a login system in which I want to display the specific data to specific user like if a user uploads something to the database so only that user should be able to see that file. I am expecting a few codes to get an idea for the logic. -
How can I delete unapplied migrations?
I would like to delete only unapplied migrations, showmigrations gives: [X] 0011_auto_20190917_1522 [X] 0012_auto_20190917_1600 [ ] 0013_auto_20190917_1638 [ ] 0014_auto_20190917_1647 [ ] 0015_auto_20190917_1652 [ ] 0016_auto_20190917_1654 [ ] 0017_auto_20190917_1704 ... I have 21 unapplied migrations! The question is when migrations are unapplied, don't have any effect on database, right? Can I just delete them from "myapp" migrations folder and after that to do makemigrations and migrate again? -
django setup in pycharm
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Requirement already satisfied: virtualenvwrapper-win in ./.local/lib/python2.7/site-packages (1.2.5) Requirement already satisfied: virtualenv in ./.local/lib/python2.7/site-packages (from virtualenvwrapper-win) (16.7.5) I am getting error while setting up Django in Pycharm using terminal. can anyone give me step by step tutorial for setting up Django in Pycharm.. Blockquote -
How to validate phone number in django?
I'm currently using phonenumbers package as a validation method to my django's UserCreationForm for its phone number field. In my current code I am using a get method to retrieve the phone number from its field and then do the validation. If the entered number does not exists, a form error is supposed to pop up and state that the number is not in a country's format (in this case i'm using singapore). Please tell me what changes should be made to my current code. I've tried using "from phonenumber_field.formfields import PhoneNumberField" for the phone number validation and it validates the number I've entered, the only problem is that the users will have to type their country code and I cannot have that. I'm using just the phonenumbers package so that users will not have to enter the country code. /* forms.py */ import phonenumbers from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from validate_email import validate_email from phonenumber_field.formfields import PhoneNumberField class UserRegisterForm(UserCreationForm): email = forms.EmailField() # phone_number = PhoneNumberField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', 'email', 'phone_number'] def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, verify=True): raise forms.ValidationError("Invalid email") return … -
Django -- show download file link on html page based on latest ID
I have a form with fields and upload file option. I show the data of the form in a HTML view, fetching the latest form with the latest ID. however the link of the uploaded file does not work. Is there something i must still add to the url When i click on the link it says no url found models.py class Metadataform(models.Model): id = models.AutoField(primary_key=True) Name = models.CharField(max_length=500, blank=True, null=True) Document = models.FileField(upload_to='uploads/') urls.py path('list/listdec/<int:pk>/', views.listdec, name='listdec'), list.html <h2> {{c.id}} </h2> {% csrf_token %} <div class="panel panel-default"> <div class="panel-body"> <p class="bold">Authors Name:</p>{{c.Authors_Name}} </div> <div class="panel-body"> <p class="bold">Dataset:</p> <a href="{{ c.Document.url }}" class="btn btn-primary btn-sm">{{ c.Document}}</a> </div> -
Django admin Inline: how to make a custom str() function for a field?
Inline declaration is very simple: class MyModelInline(admin.StackedInline): model = MyModel fk_name = 'my_fk' fields = ('my_field', ) extra = 0 verbose_name = _("My field") verbose_name_plural = _("My fields") But Django calls MyModel.__str__ to convert it as a string. Although you can easily change that in classical admin fields, I didn't find a way to make my "custom" str field like this: class MyModelInline(admin.StackedInline): def i_laugh_often_too_loud(self, obj): return 'custom text' # str(obj) i_laugh_often_too_loud.allow_tags = True i_laugh_often_too_loud.short_description = _("Person") model = MyModel fk_name = 'my_fk' fields = ('my_field', 'i_laugh_often_too_loud') extra = 0 verbose_name = _("My field") verbose_name_plural = _("My fields") When I do this I get: Unknown field(s) (i_laugh_often_too_loud) specified for MyModel How to make this work and have 'custom text' displayed? -
cannot convert float NaN to integer
I am trying to upload CSV data in MySQL table but my CSV has some empty columns and when I'm uploading my CSV all data before the empty columns are uploading but after that CSV upload getting a stop for i in range(m * chunksize, (m * chunksize) + chunksize): company = pd.isnull(df.loc[i]['company'] or df.loc[i]['name'] or df.loc[i]['observed_sales'] or df.loc[i]['observed_transactions']) if company == True : df.loc[i]['company'] = '' df.loc[i]['name'] = '' y = np.nan_to_num(df.loc[i]['observed_sales']) z = np.nan_to_num(df.loc[i]['observed_transactions']) df.loc[i]['observed_sales'] = df.loc[i]['observed_sales'].replace('nan', np.nan).interpolate(0.0) df.loc[i]['observed_transactions'] = df.loc[i]['observed_transactions'].replace('nan', np.nan).interpolate(0.0) Company.objects.update_or_create(company_name=df.loc[i]['company'], company_full_name=df.loc[i]['name'], website_url=df.loc[i]['website']) obj = Company.objects.latest('company_id') id = obj.company_id TransactionDetails_Monthly.objects.update_or_create(company_id=id, observed_sales=y, observed_transactions=z, observed_customers=df.loc[i]['observed_customers'], sales_per_customer=df.loc[i]['sales_per_customer'], txns_per_customer=df.loc[i]['txns_per_customer'], avg_txn_value=df.loc[i]['avg_txn_value'], month=df.loc[i]['month']) msg = "Data is inserted successfully" I'm facing this error [cannot convert float NaN to integer] and I also want to show my models.py class Company(models.Model): company_id = models.AutoField(primary_key=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True) #ForeignKey company_name = models.CharField(max_length=255,null=True) company_full_name = models.CharField(max_length=255, null=True) company_name_url = models.CharField(max_length=255, null=True) website_url = models.CharField(max_length=255, null=True) founded_date = models.DateField(null=True) founded_date_precision = models.DateField(null=True) total_funding_amount = models.DecimalField(max_digits=13, decimal_places=2, null=True) total_funding_amount_currency = models.DecimalField(max_digits=13, decimal_places=2, null=True) total_funding_amount_currency_usd = models.DecimalField(max_digits=13, decimal_places=2, null=True) class TransactionDetails_Monthly(models.Model): transaction_id = models.AutoField(primary_key=True) company = models.ForeignKey('Company' , on_delete = models.CASCADE, null=True) #ForeignKey month = models.DateField() observed_sales = models.IntegerField() observed_transactions = models.IntegerField() observed_customers = models.IntegerField() sales_per_customer = … -
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?