Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django decorator keyError
I wanted to write a decorator to restrict users from viewing/editing/deleting other users entries but it's causing a value error. here's the decorators.py from django.core.exceptions import PermissionDenied from functools import wraps from .models import Mymodel # decorator for checking objects created by users and restricting access to them def user_is_entry_creator(function): @wraps(function) def wrap(request, *args, **kwargs): entry = Mymodel.objects.get(pk=kwargs['pk'])#the error here if entry.user == request.user: request.entry = entry return function(request, *args, **kwargs) else: raise PermissionDenied return wrap I know where's the error from but i don't know how to write it right. -
How to made a loop and not to use destination function again and again? [duplicate]
This question already has an answer here: How to make a loop in views.py in django 2 answers I want to make this Destination() once. But whenever I add c and more alphabets to the target, the pictures and description repeats itself. I don't want this destination function to be repeated again and again. def index(request): target = a, b, c, d = [Destination() for __ in range(4)] a.img = f'0{1}.jpg' b.img = f'0{2}.jpg' c.img = f'0{3}.jpg' d.img = f'0{4}.jpg' a.desc = 'Hello, How are you!' b.desc = 'Hello, How are you!' c.desc = 'Hi, I am fine.' d.desc = 'Hi, I am fine.' context = { 'target': target, } return render(request, 'index.html', context) -
Uncaught TypeError: $(...).skillbar is not a function at HTMLDocument.<anonymous>
I am currently learning Django. At the moment, I want to apply Jquery in my Web, and I receive this error: jquery-3.4.1.min.js:2 Uncaught TypeError: $(...).skillbar is not a function at HTMLDocument.<anonymous> (VM350 main.js:2) When I open my main.js, I surprisingly find that my main.js become $(document).ready(function () { $('.skillbar').skillbar({ speed: 1000, }); }); I have attached my main.js here. Thanks for any help and advice (function ($) { "use strict"; /*================================================================== [ Focus input ]*/ $('.input100').each(function(){ $(this).on('blur', function(){ if($(this).val().trim() != "") { $(this).addClass('has-val'); } else { $(this).removeClass('has-val'); } }) }) /*================================================================== [ Validate ]*/ var input = $('.validate-input .input100'); $('.validate-form').on('submit',function(){ var check = true; for(var i=0; i<input.length; i++) { if(validate(input[i]) == false){ showValidate(input[i]); check=false; } } return check; }); $('.validate-form .input100').each(function(){ $(this).focus(function(){ hideValidate(this); }); }); function validate (input) { if($(input).attr('type') == 'email' || $(input).attr('name') == 'email') { if($(input).val().trim().match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) { return false; } } else { if($(input).val().trim() == ''){ return false; } } } function showValidate(input) { var thisAlert = $(input).parent(); $(thisAlert).addClass('alert-validate'); } function hideValidate(input) { var thisAlert = $(input).parent(); $(thisAlert).removeClass('alert-validate'); } })(jQuery); -
I keep getting the following error when I submit my register form data
I am trying to the create a bank system using DRF. I need to automatically assign users an account number immediately they fill in their registration details. Other than this, kindly pardon me if I do not have the right question-asking skills. I am using django --version 2.2.3 models.py class AccountDetails(models.Model): GENDER_CHOICE = ( ("M", "Male"), ("F", "Female"), ) user = models.OneToOneField( User, related_name='account', on_delete=models.CASCADE, ) account_no = models.AutoField( unique=True, primary_key=True, null=False, validators=[ MinValueValidator(10000000), MaxValueValidator(99999999) ] ) views.py def register_view(request): if request.user.is_authenticated: return redirect("home") else: user_form = UserRegistrationForm( request.POST or None, ) account_form = AccountDetailsForm( request.POST or None, request.FILES or None ) address_form = UserAddressForm( request.POST or None ) if user_form.is_valid() and account_form.is_valid() and address_form.is_valid(): user = user_form.save(commit=False) account_details = account_form.save(commit=False) address = address_form.save(commit=False) password = user_form.cleaned_data.get("password1") user.set_password(password) user.save() account_details.user = user account_details.save() address.user = user address.save() new_user = authenticate( account_no=user.account_no, password=password ) login( request, new_user, backend='accounts.backends.AccountNoBackend' ) messages.success( request, '''Thank You For Creating A Bank Account {}. Your Account Number is {}, Please use this number to login '''.format(new_user.full_name, new_user.account_no)) return redirect("home") context = { "title": "Create a Bank Account", "user_form": user_form, "account_form": account_form, "address_form": address_form, } return render(request, "accounts/register_form.html", context) the following is the output: AttributeError at /accounts/register/ … -
Unable deserialize non-model field in modelSerializer in DRF3
This question might seem redundant but I have searched for other answers and they didn't seem to solve the problem. I am using GeoDjango with DRF3. I have a field in my models named location, whose value is given as Point instance which takes longitude and latitude as argument. Therefore, in serializer I have two non-model fields - latitude and longitude. However, when I print the validated_data, lat and lng aren't getting deserialized. models.py class Site(models.Model): site_id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="site") location = models.PointField(geography=True, null=True, blank=True) area = models.FloatField(null=True) objects = SiteManager() managers.py class SiteManager(BaseManager): use_in_migrations = True def create(self, owner, **kwargs): print('kwargs is ',kwargs) site = self.model( owner = owner, area = kwargs['area'], location=Point(float(kwargs['longitude']), float(kwargs['latitude'])), ) site.save(using=self._db) print('site is ',site) return site serializers.py class SiteSerializer(serializers.ModelSerializer): latitude = serializers.SerializerMethodField() longitude = serializers.SerializerMethodField() def get_latitude(self, validated_data): print(validated_data['latitude']) def get_longitude(self, validated_data): print(validated_data['longitude']) class Meta: model = Site fields = ('latitude', 'longitude', 'area') # Serializer to get user details class UserSiteSerializer(serializers.ModelSerializer): site = SiteSerializer() class Meta: model = User fields = ('fullName', 'email', 'site') def create(self, validated_data): site_data = validated_data.pop('site') user = InterestedUser.objects.create(**validated_data) Site.objects.create(owner=user, **site_data) return user Request data is {'fullName': 'rtyhgf', 'email': '8sdfggfs@er.com', 'site': {'longitude': 77.48538458919909, 'latitude': … -
Creating Profile with rest-social-auth
I have recently used rest-social-auth for my project and it returns me a jwt token with this token users should be able to create their profile but I do not know if my method is right or wrong because I am relatively new to Django world. To create a profile my models.py class Profile(models.Model): user = models.OneToOneField('authentication.CustomUser', primary_key=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) avatar = models.ImageField(upload_to=path) nationality = models.CharField(max_length=20) def __str__(self): return self.user.email my serializers.py file as follow class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['first_name', 'last_name', 'avatar', 'nationality'] is this method to create a profile correct? but when I test the api it gives me a error Foreign Key constraint failed please can you tell me the correct way to create a profile? -
Unable to save new databse item with foreignkey
I have an issue with django app. I have a form to add new Category and an other one to add Subcategory. Subcategory has a foreignkey to Category, you can find models.py below: models.py nom = models.CharField(primary_key=True, max_length=100) description = models.TextField(blank=True) class SousCategorie(models.Model): nom = models.CharField(primary_key=True, max_length=100) categorie = models.ForeignKey(Categorie, on_delete=models.DO_NOTHING) description = models.TextField(blank=True) I have a form to create new Subcategory item in forms.py nom = forms.CharField() categorie = forms.ModelMultipleChoiceField(queryset=Categorie.objects.all()) description = forms.CharField() class Meta: model = SousCategorie fields = ['nom', 'categorie', 'description'] Problem is i use a queryset to make a list with all category items but when i want to save my item, it says that cannot assign queryset because it have to be a category instance: views.py form = SousCategorieForm(request.POST) nom = request.POST["nom"] categorie = request.POST["categorie"] description = request.POST["description"] souscategorie = form.save(commit=False) souscategorie.nom = nom souscategorie.categorie = categorie souscategorie.description = description souscategorie.save() And the error : Cannot assign "]>": "SousCategorie.categorie" must be a "Categorie" instance. Can you help me to solve this issue? Thank you, Romain BOULAY -
Django allauth access request in custom signup form
I want to access the request object in the init method of django allauth the custom form code i have class CustomSignupForm(SignupForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'email' in self.request.session: self.fields['email'].value = self.request.session['email'] self.fields['email'].disabled = True def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user -
How to add key value pair to django queryset
I want to show stats for account by account in for loop of template. In list of dicts or querysets. I have 3 models: (1)AdvertisingAccount, (2)Campaign, UserProfile. I need to sum() clicks and views of Campaigns that belongs to certain AdvertisingAccounts by Foreign Key. (AdvertisingAccount also belongs to UserProfile ) Im trying to retrieve, calculate and add new key-value to dicts of queryset, but seems like I cant do it in dict method… views.py def ad_accounts(request): user = request.user accounts = user.userprofile.advertising_accounts.all() accounts = accounts.values() for d in accounts: d.update(('clicks', d.campaigns.all().aggregate(Sum('clicks')) ) for k,v in d.items()) d.update(('views', d.campaigns.all().aggregate(Sum('views')) ) for k,v in d.items()) models.py class AdvertisingAccount(models.Model): balance = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True, null=True) foreign_system_name = models.CharField(max_length=30, blank=True, default=None) foreign_system_id = models.IntegerField(default=None, blank=True, null=True) def __str__(self): return self.foreign_system_name + '--' + str(self.foreign_system_id) class Campaign(models.Model): userprofile = models.ForeignKey('users.UserProfile', on_delete=models.PROTECT, related_name='campaigns') trade = models.ForeignKey('payments.Trade', on_delete=models.PROTECT, related_name='campaigns') ad_account = models.ForeignKey('AdvertisingAccount', on_delete=models.PROTECT, related_name='campaigns') views = models.IntegerField(default=0, blank=True, null=True) clicks = models.IntegerField(default=0, blank=True, null=True) ad_spent = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True, null=True) def __str__(self): return str(self.userprofile) + '--' + str(self.ad_account.foreign_system_name) + '--' + str(self.trade.ad_budget) template {% for i in accounts %} {{i.clicks}} {{i.views}} {% endfor %} I got error :'dict' object has no attribute 'campaigns' As I … -
How can I query and compare the values of a JSONbField on an object?
I have a model that contains a jsonbfield, and need to query the values of the dictionary. Within a query, I need to ensure that all the values of the dictionary are None, or that the entire field is None. My model looks like: MyModel(models.Model): date_created=DatetimeField() json_dict = JSONField(default=None) Essentially I want to get something like: MyModel.objects.filter(Q(json_dict=None) | Q(all(v=None for v in json_dict.values()))) But I cannot do that in a query. I was wondering if there was a way to check this while keeping the results in a queryset, rather than evaluating it into a list and checking there. One limitation is that I do not know the keys of the dictionary as they will be different for every object in MyModel. -
Suggestions for web deployment of prototype
I have prototyped a system using python on linux. I am now designing the architecture to move to a web based system. I will use Django to serve public and private admin pages. I also need a service running, which will periodically run scripts, connect to the internet and allow API messaging with an admin user. Thus there will be 3 components : web server, api_service and database. 1) What is best mechanism for deploying a python api_service on the VM? My background is mainly C++/C# and I would have usually deployed a C#-written service on the same VM as the web server and used some sort of TCP messaging wrapper for the API. My admin API code will be ad hoc python scripts run from my machine to execute functionality in this service. 2) All my database code is written to an interface that presently uses flat-files. Any database suggestion? PostgreSQL, MongoDB, ... Many thanks in advance for helpful suggestions. I am an ex-windows/C++/C# developer who now absolutely loves Python/Cython and needs a little help please ... -
'ModelBase' object is not iterable
when I get all profiles from the database I take following error Traceback (most recent call last): File "/home//venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/venv/lib/python3.7/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/home/venv/lib/python3.7/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/home/venv/lib/python3.7/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/home/venv/lib/python3.7/site-packages/rest_framework/generics.py", line 241, in get return self.list(request, *args, **kwargs) File "/home/venv/lib/python3.7/site-packages/rest_framework/mixins.py", line 48, in list return Response(serializer.data) File "/home/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 768, in data ret = super(ListSerializer, self).data File "/home/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 262, in data self._data = self.to_representation(self.instance) File "/home/venv/lib/python3.7/site-packages/rest_framework/serializers.py", line 686, in to_representation self.child.to_representation(item) for item in iterable TypeError: 'ModelBase' object is not iterable [11/Jul/2019 10:15:06] "GET /profile/ HTTP/1.1" 500 24593 Internal Server Error: /profile/ I easily create profile with post method but getting all profiles are problem. my models.py file class Profile(TimeModel): user = models.OneToOneField('user_accounts.CustomUser', primary_key=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) birthdate = models.DateTimeField(null=True) image = models.ImageField(upload_to='profile_images', null=True) def __str__(self): return self.user.email … -
Django admin change error message ("Please correct the errors below.")
Is it possible to change django admin error message. i want add my custom error message. Please correct the errors below. change this message class mymodel(admin.ModelAdmin): # change message -
What is the purpose of the `Retail price` field in the django oscar dashboard?
I've attempted to input a value for the Retail price field in the django oscar dashboard in both versions 1.6 and 2.0 for a dummy product, however, no visible changes were observed in the product detail pages, nor does checking out reflect the retail price. I went through the source code a bit, and I found some comments indicating that retail price, along with some other items will be depracated in django oscar 2.1. Does this mean that the Retail price field in the dashboard is not meant to be used by new projects, and is simply there for those who have used this in the past? -
Adding a database in Pycharm
I have made a project in Pycharm using Django and a virtual environment using conda commands. By default the database added in it is db.sqlite3 but I want to change it to MySQL which I have preinstalled in my laptop. I also installed the database navigator package in the Pycharm and a connection with the preinstalled MySQL has been setup. But how to link it with my current project in place of db.sqlite3. -
Not abel to connect django1.11 with oracle11g
I am not able to migrate project in linux.Dependecy:cx-Oracle==7.2.0 Django==1.11,oracle11g and python3.I am trying to connect with a server database. I removed a line" self.cursor.numbersAsStrings = True" from "/work/sunlife_env/lib/python3.6/site-packages/django/db/backends/oracle/base.py" to resolve this error:""AttributeError: 'cx_Oracle.Cursor' object has no attribute 'numbersAsStrings'" BUT now after,python manage.py migrate,i am getting followig error. Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/init.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 250, in apply_migration self.recorder.record_applied(migration.app_label, migration.name) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in record_applied self.migration_qs.create(app=app, name=name) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/query.py", line 393, in create obj.save(force_insert=True, using=self.db) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/base.py", line 806, in save force_update=force_update, update_fields=update_fields) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/base.py", line 836, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/base.py", line 922, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/base.py", line 961, in … -
Can we make changes to the django packages
Is it okay to make changes to the django packages? For instance in my project I have a folder lib/python2.7/site-packages/reversion/ And in here I want to add one method inside of models.py Is this correct? Initially I wanted to edit django's admin history page. In some models history change messages are shown in unicode format, but I need it to be string readable. In models.py I used eval function to transfer unicode to python list. Pleaaaaaase help! -
Django get a foreign key from a foreign key in queryset
I'm trying to get a foreign key of a foreign key in 1 query but I can't make it work Models class Storage(models.Model): name = models.CharField(max_length=200, null=False, blank=False, unique=True) class Freezer(models.Model): name = models.CharField(max_length=200, null=False, blank=False, unique=True) storage = models.ForeignKey(Storage, models.CASCADE, blank=True, null=True, related_name='freezer') class Rack(models.Model): name = models.CharField(max_length=200, null=False, blank=False, unique=True) freezer = models.ForeignKey(Freezer, models.CASCADE, blank=True, null=True, related_name='rack') Code This works when I get all the freezers display_text = ", ".join([ "<a href={}>{}</a>".format( reverse( 'admin:{}_{}_change'.format("admin", "freezer"), args=(items.pk, )), items) for items in obj.freezer.all() ]) if display_text: return mark_safe(display_text) But I cannot get the rack on this query display_text = ", ".join([ "<a href={}>{}</a>".format( reverse( 'admin:{}_{}_change'.format("admin", "rack"), args=(items.pk, )), items) for items in obj.freezer.rack,all() ]) if display_text: return mark_safe(display_text) Any suggestions sorry I'm new? -
writing the output of the View to a file named after Date and time
When printing the output to the webpage, its working fine.! Now,i m trying to add a button which when clicked, A) prints the current output(IP entered, command ran, output produced) to a file in defined directory B) the file should be named after current Date and time. i have gone through several answers on Stackoverflow but it was not fruitful :-( Here's My code:- views.py from django.shortcuts import render from first_app.forms import CmdForm from django.http import HttpResponse import datetime # Create your views here. def index(request): my_dict = {'insert_me': ""} return render(request,'first_app/index.html',context=my_dict) def form_name_view(request): if request.method == "POST": form = CmdForm(request.POST) if form.is_valid(): from netmiko import ConnectHandler ipInsert = request.POST.get('ip_address', '') devices = { 'device_type':'cisco_ios', 'ip':ipInsert, 'username':'mee', 'password':'12345', 'secret':'12345', } cmd = request.POST.get('command', '') netconnect = ConnectHandler(**devices) getIP = netconnect.send_command(ipInsert) output = netconnect.send_command(cmd) now = datetime.datetime.now().strftime('%D %H:%M:%S') return render(request,'first_app/forms.html', {'form': form, 'output':output, 'getIP':getIP, 'date_time':now}) else: form = CmdForm() return render(request,'first_app/forms.html', {'form': form}) else: return render(request,'first_app/forms.html', {}) def export_output_function(request): if(request.Get.get('export_button_name')): with open(now + '.txt', 'w+') as f: print (f.form_name_view.getIP) print (f.form_name_view.cmd) print (f.form_name_view.now) print (f.form_name_view.output) return render(request,'first_app/forms.html', {'print_output':print_output}) else: return render(request,'first_app/forms.html') forms.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>FORMS</title> </head> <body> <h1> IP address form … -
How to detect if a Model property is a foreign key relation? (And retreive all FK Model objects)
I'm trying to create a table that propagates dynamically with django objects, where each row is a django model object. If the object property is a foreign key, the goal is to display a drop-down list of all the possible FK options. To do this, I'll need to detect if the object field is an FK and then retrieve all FK objects. There are two components to this: I'm struggling to determine if the object property is an FK relationship I'm struggling to get all object of the same model as the FK The idea in pseudocode would be: for field in object.fields: if field is FK: return field.objects.all() else: return field I know that I can test for a ForwardManyToOneDescriptor relation (below), but is there a more compact general way to test for a FK relationship? isintance(Foo.bar, db.models.fields.related_descriptors.ForwardManyToOneDescriptor): Is there any way of getting all of the model objects of the FK, either by the model class or an instance of the class? Foo.bar.all() or Foo.objects.first().bar.all() -
How can I make attrs for form email and password fields?
I managed with making attrs for TextInput, but it doesn't work for EmailInput and PasswordInput... My Registration form: class RegisterForm(UserCreationForm): email = forms.EmailField(label = "Email") class Meta: model = User fields = '__all__' widgets = { 'username': forms.TextInput(attrs = {'class': 'nice_input', 'placeholder': 'Name'}), 'email': forms.EmailInput(attrs = {'class': 'nice_input', 'placeholder': 'Email'}), 'password1': forms.PasswordInput(attrs = {'class': 'nice_input', 'placeholder': 'Password'}), 'password2': forms.PasswordInput(attrs = {'class': 'nice_input', 'placeholder': 'Password confirmation'}), } def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['password1'].help_text = '' self.fields['password2'].help_text = '' Everything is ok with username field, but not with others... Also when I change an email field into text field it works ###### email = forms.EmailField(label = "Email") 'email': forms.TextInput(attrs = {'class': 'nice_input', 'placeholder': 'Email'}), What should I try? -
How to add users in any model from template in django?
In models: class Match(models.Model): user = models.ManyToManyField(User, blank=True) player_name = models.CharField(max_length=30, null=True, blank=True) player_credit = models.IntegerField(null=True, blank=True) hot_league = models.ManyToManyField('HotLeague', blank=True) class HotLeague(models.Model): user = models.ManyToManyField(User, blank=True) price_pool = models.IntegerField() winner = models.IntegerField() entry = models.IntegerField() In views: def hot_league_details(request, match_id, hot_league_id): match = get_object_or_404(Match, pk=match_id) hot_league = get_object_or_404(match.hot_league, pk=hot_league_id) context = { 'match': match, 'hot_league': hot_league, } return render(request, 'main/hot_league_details.html', context=context) In templates: <div class="col"> Price Pool <h4 style="color:red;" class="pt-1">TK. {{ hot_league.price_pool }}</h4> </div> <div class="col text-center" style="font-size: 12px; padding-top: 5px;"> <div>{{ hot_league.winner }} Winners</div> <div class="d-flex justify-content-end"> <button type="button" class="btn btn-danger btn-sm">TK. {{ hot_league.entry }}</button> </div> </div> Here in template, when any user press the button then in my Match and HotLeague model objects, that QuerySet will update with this user automatically..Using admin site I don't add any user query manually, it will update by actual user from pressing button in template... Like, in any online market place when user add any product in cart then all the information of that product can access by this user from his cart.. Different user can add different product in their cart and can access that product details from their cart... How can I do this in here??? -
How to add images in email with django allauth
I have troubles with django allauth Here's my template password_reset_key_message.txt {% autoescape off %} {% load static from staticfiles %} {% load i18n %}Hello{% if username %}, {{ username }}{% endif %}! {% if username %}{% blocktrans %}In case you forgot, your username is {{ username }}.{% endblocktrans %}{% endif %} You're receiving this e-mail because you or someone else has requested a password for your user account. It can be safely ignored if you did not request a password reset. Click the link below to reset your password. {% load static %} <img src="{% static "avatar.jpg" %}" alt="avatar" /> {{ password_reset_url }} {% if username %}{% blocktrans %}In case you forgot, your username is {{ username }}.{% endblocktrans %} {% endif %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Thank you for using {{ site_name }}! {{ site_domain }}{% endblocktrans %} {% endautoescape %} I'm trying to add image in email body (already trying with link on source and converting image to base64) But when I click on reset_email I got this result: -
Django-Rest-Framework endpoint not accessing my database collection
I'm trying to create an API endpoint for my django project. In this project, i have two databases: a SQLite database and a MongoDB database; the data that i'm trying to retrieve is on my Mongo database, on a collection called tst. So on this collection there is already some data. I created the endpoint, then i opened my browser to go to http://127.0.0.1:8000/tst/, expecting to find that data there in json format, but it looks like the endpoint doesn't see any data, although i'm sure it is. Can someone help me find what i'm doing wrong? Here is my model: class tst(models.Model): id = models.CharField(max_length=100) ticker = models.FloatField() def save(self): # ALL the signature super(tst, self).save(using='dbtwo') Here is my view: class tstList(generics.ListCreateAPIView): queryset = tst.objects.using('dbtwo').all() serializer_class = tstSerializer Here is the serializer: class tstSerializer(serializers.ModelSerializer): class Meta: model = tst fields = ('id', 'Ticker', ) And the url: path('tst/', views.tstList.as_view()), -
How can I add django-cms articles specific to a page template created using html and django views?
I am creating a page on my website where I need a section where I can pull data for an item X from the SQL database associated with the django models and another section where I need to put an article created/written specifically for that item X. similarly, for all items in that model, I will need to do the same. There must be a way to save the articles with IDs of items in django models, so I can pull the linked articles. I have gone through the django-cms docs and read about 'page lookups' but haven't been able to implement it. Adding any article is easy using aldryn-form plugins but I need to have an artcile from the DB specifically related to that item.