Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django annotation using data from another table without relations
What I'm trying to do is annotate a queryset with information from a few tables that don't have foreign key relations between them, but can be identified from values in the main table. I realise that I could add relations and do something like this, but the db I'm using doesn't allow for relations. So given models: class DailyShopData(models.Model): shop_id = models.IntegerField() currency = models.CharField() date = models.DateField() amount = models.IntegerField() class Meta: unique_together = ('shop_id', 'date', 'currency') class DailyUserData(models.Model): shop_id = models.IntegerField() currency = models.CharField() date = models.DateField() unique_users = models.IntegerField() class Meta: unique_together = ('shop_id', 'date', 'currency') We can relate the two fields via the ('shop_id', 'data_date', 'currency') key. So what I'd like to do for my annotation is: DailyShopData.objects.values('shop_id').annotate( shop_amount=Sum("amount"), shop_unique_users=Sum(???) ) So that the result would be aggregated amount and unique_users per shop_id. -
Django RF + React JS, How to check in frontend whether any user is being logged in?
I use Django Rest Framework in backend and React in frontend for my Blog project. In Django templates if we use {{user}} method, we will know if anybody being logged in. But I am unable to use the above method in React JS environment. Should I send a test create (POST) request to server to check that ? Any better idea ? -
Django - multiple form choice field values not saving in model correctly
I am new to Django and have a ChoiceField form which I am using multiple times on the same html page. I have successfully saved all these values to the database. However, the values are saving incorrectly. If the choices are different on each form, they are saved in the table as the first value (APPLE). If the choices are all APPLE or all ORANGE they save correctly. But if they are mixed they don't save properly. Any ideas on what is happening here or how to fix the issue? Please see Form, View and HTML below. FORM: FRUIT = ( ("APPLE", "APPLE"), ("ORANGE", "ORANGE"), ) class SubmitFruitForm(forms.ModelForm): preference = forms.ChoiceField(choices=FRUIT, required=False, label= '') class Meta: model = user_choice fields = ('preference',) VIEW: class SubmitFruitView(TemplateView): template_name = 'accounts/fruit.html' def get(self, request): form1 = SubmitFruitForm() form2 = SubmitFruitForm() form3 = SubmitFruitForm() return render(request, self.template_name, {'form1': form1, 'form2': form2, 'form3': form3}) def post(self, request): form1 = SubmitFruitForm(request.POST) form2 = SubmitFruitForm(request.POST) form3 = SubmitFruitForm(request.POST) if form1.is_valid(): post = form1.save(commit=False) post.user = request.user post.save() if form2.is_valid(): post = form2.save(commit=False) post.user = request.user post.save() if form3.is_valid(): post = form3.save(commit=False) post.user = request.user post.save() return redirect('home') args = { 'form1': form1, 'form2': form2, 'form3': form3, } … -
Django inlineformset: UpdateView doesn't work
I am neewbie in django and moreover with inlineformset. I have follow this tutorial to implement inlneformset. CreateView works (data are registered in database) but UpdateView doesn't. UpdateView is correctly displayed with correct datas. But it seems that subform (application inlineformset) is never valid and I don't understand why... UpdateView: class UtilisateurUpdateView(UpdateView): model = Utilisateur fields = ['uti_nom','uti_pre','uti_mai','uti_sit','uti_pro'] def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["utilisateur"] = self.request.user.username data["application"] = ApplicationFormset(self.request.POST, instance=self.object) else: data["application"] = ApplicationFormset(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() application = context["application"] self.object = form.save() self.object.save() if application.is_valid(): # ***** NEVER VALID ***** application.instance = self.object print('application.instance',application.instance) application.app_app_nom = application.instance.cleaned_data['app_app_nom'] application.app_dro = application.instance.cleaned_data['app_dro'] application.app_log = context["utilisateur"] application.uti_ide = 1 application.save() return super().form_valid(form) def get_success_url(self): return reverse("project:index") -
Django-allauth reloads page twice after LOGIN_REDIRECT
I am using Django-allauth for user registration with social networks. Either with Google or with Facebook, when the login is performed, I see how my index page is reloaded twice. My allauth settings: SOCIALACCOUNT_PROVIDERS = \ { 'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'rerequest'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'path.to.callable', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'}, 'google': { 'SCOPE': ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'], 'AUTH_PARAMS': {'access_type': 'online'}, } } ACCOUNT_EMAIL_VERIFICATION = 'none' My other settings which might be relevant: LOGIN_URL = "/login/" LOGIN_REDIRECT_URL = "/" LOGOUT_REDIRECT_URL = '/' I have tried using an account adapter and redirecting to another URL, but I always see this target page reloaded twice. Any ideas how to avoid this behaviour? -
Strange Request failed with status code 401 axios
im recieving this error message in my console. The technology stack im using is django , react ,redux , djangosimple-jwt. createError.js:16 Uncaught (in promise) Error: Request failed with status code 401 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61) This happens when i log out from my application and relog back without refreshing the page. class CustomerList extends Component { state = { customers: [], }; apiGet() { try { axiosInstance.get('/customer-information/') .then(response => { this.setState({ customers: response.data }); $('#customerlist').DataTable({ "scrollY": "70vh", "scrollCollapse": true, "paging": false, "scrollX": true }); }) } catch (error) { console.log(error.stack); } } componentDidMount() { console.log('comp did mount ') #<---- here is where the error comes from. If the page is mounted without any refreshing , it calls the apiGet but returns the 401 error if (this.props.access_token) { console.log('comp did mount ' + this.props.access_token) this.apiGet() }; }; componentDidUpdate(oldProps) { #<------the call to apiGet does not seem to have a problem here in componentDidUpdate if (this.props.access_token !== oldProps.access_token) { console.log('comp did update ' + this.props.access_token) this.apiGet() } }; render() { const { customers } = this.state; return ( <Layout style={{ background: '#fff', height: '100vh', padding: '3%' }}> <h3>Customer List</h3> <Link to='/customer/create'> <p>Create a Customer</p> </Link> <div className="container" … -
Redirect to a specific private page with LoginRequiredMixin after login
When trying to access a private page, this view redirects to the login page if the user is not authenticated, and after the authentication was done, I wanted it to redirect to the private page instead of success_url, with LoginView configured for a FormView. When I access the private page without logging in, this standard url is generated according to django http://localhost/myapp/login/?next=/myapp/private-page/, in this case the url that will be redirected after login should be myapp/private-page instead of success_url My code looks like this: # myapp/urls from django.urls import path from . import views app_name = 'myapp' urlpatterns = [ path("", views.home, name='home'), path("login/", views.LoginRequest.as_view(), name='login'), path('logout/', views.logout_request, name='logout'), path("signup/", views.signup, name='signup'), path("private-page/", views.PrivatePage.as_view()), ] # myapp/views.py class PrivatePage(LoginRequiredMixin, TemplateView): template_name = 'myapp/private-page.html' login_url = 'myapp:login' class LoginRequest(FormView): template_name = 'myapp/auth/login/login.html' form_class = LoginForm success_url = 'myapp:home' def form_valid(self, form): """If the form is valid, redirect to the supplied URL.""" username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(self.request, user) messages.info(self.request, f'You are connected as {username}') # here the code to redirect to the private-page # instead this return return redirect(self.get_success_url()) else: self.form_invalid(form) def form_invalid(self, form): """If the form is invalid, render the … -
How do I pass the same name to a more details page in Django?
I have a Django web app and I have a several bootstrap cards on my index page with a name, an image and a button which redirects to a "more details" page on my website. In android, it's like passing data to the next activity using an intent. How do i pass the name on my cards to a more details page? Provided that each name is the one that I click. Image of my website Thanks! -
Why are some Elastic Search records disappearing
I have a Django application using ElasticSearch (via django-elasticsearch-dsl==7.1.1) and I have certain records that are disappearing from my searches (ie they show one day but not the next). If you save the record (no update required) they appear in the search again. I don't know how to start trying to trouble shoot this and would welcome any guidance. This is is my function returning ES data: def brand_suggestions(request): """ Returns a json response with suggestions of organisation names based on the search query received. This view is queried by an ajax request as the user types their search query. """ if not request.is_ajax(): raise Http404() search = request.GET.get('search') search_term=search suggestion_type='name_suggestions' field='name_suggestion' sqs = documents.BrandDocument.search() search_term = search_term.split() # make into wildcard search query = Q('match', brand_is_active=True) for term in search_term: query = Q(Q(query) & Q('wildcard', name=term.lower()+"*")) sqs = sqs.query(query) # query the index for organisation name suggestions based on the query entered so far sqs = sqs.suggest(suggestion_type, text=search_term, completion={'field': field}) # suggestion data returned includes 'payload' dict with postcode/town data = sqs.execute(ignore_cache=True).to_dict()['hits']['hits'] suggestions = [] for suggestion in data: score = suggestion['_score'] #suggestion = suggestion['_source']['brand_name_suggestion'] suggestions.append({ 'text': suggestion['_source']['brand_name_suggestion'], 'score': score, 'payload': { 'name': suggestion['_source']['name'], 'cqc_id' : suggestion['_source']['cqc_brand_id'], 'pk': suggestion['_id'], … -
How to run Django with Uvicorn webserver?
I have a Django project running on my local machine with dev server manage.py runserver and I'm trying to run it with Uvicorn before I deploy it in a virtual machine. So in my virtual environment I installed uvicorn and started the server, but as you can see below it fails to find Django static css files. (envdev) user@lenovo:~/python/myproject$ uvicorn myproject.asgi:application --port 8001 Started server process [17426] Waiting for application startup. ASGI 'lifespan' protocol appears unsupported. Application startup complete. Uvicorn running on http://127.0.0.1:8001 (Press CTRL+C to quit) INFO: 127.0.0.1:45720 - "GET /admin/ HTTP/1.1" 200 OK Not Found: /static/admin/css/base.css Not Found: /static/admin/css/base.css INFO: 127.0.0.1:45720 - "GET /static/admin/css/base.css HTTP/1.1" 404 Not Found Not Found: /static/admin/css/dashboard.css Not Found: /static/admin/css/dashboard.css INFO: 127.0.0.1:45724 - "GET /static/admin/css/dashboard.css HTTP/1.1" 404 Not Found Not Found: /static/admin/css/responsive.css Not Found: /static/admin/css/responsive.css INFO: 127.0.0.1:45726 - "GET /static/admin/css/responsive.css HTTP/1.1" 404 Not Found Uvicorn has an option --root-path so I tried to specify the directory where these files are located but there is still the same error (path is correct). How can I solve this issue? -
Is django model field lookup_type 'contains' case-sensitive or insensitive..?
As per documentation 'contains' field lookup is case-sensitive and 'icontains' is case-Insensitive, but I don't see any difference while i'm querying it. >>> from users.models import SnetUser >>> SnetUser.objects.get(email__contains='Satti') <SnetUser: satti> >>> SnetUser.objects.get(email__contains='satti') <SnetUser: satti> >>> obj = SnetUser.objects.get(email__contains='satti') >>> obj.email 'satti@gmail.com' Both are resulting same. Note: I'm using django's SQLite DB locally -
specific leaflet layer style to change dynamically based on django tags
Potion of my html code do do style <script type="text/javascript"> function our_Layers (map, options){ var datasets = new L.GeoJSON.AJAX("{% url 'owner' %}",{ style: function colors(feature){ switch(feature.properties.lr){ case "{{LR}}": return{ color: 'red' }; break } }, onEachFeature: function(feature, layer){ //layer.bindPopup(feature.properties.lr.toString()); layer.bindPopup('<strong>LR No.: </strong>'+ feature.properties.lr.toString() ); } }); datasets.addTo(map); } </script> {% leaflet_map "parcels" callback="window.our_Layers" %} my view in django def Usermap(request): plots1 = request.user.person.Persona.all() for Registration in plots1: LR=(Registration.parcels.lr) context = {'plots':plots1,'LR':LR} return render(request, 'Cadastre/Usermap.html', context) Have used that for loop in django to show me available lr which are 3 but i cant use django for loop tags inside the leaflet function any help -
django app doesn't find mysql database on docker
I am a noobie and I used some different tutorials to satisfy my needs for a project I'm working on. when I use the command (docker-compose run app sh -c "python manage.py test && flake8") it gives me the following error(s): Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.8/site-packages/django/test/runner.py", line 687, in run_tests … -
Django ORM: Raw query behaves different from ORM query
I'm having an issue and i can't even figure out what's the problem. I'm trying to obtain the result with the following expression using Django ORM: # Names of the models and fields are different from those on the DB. >>> readings = MeterReading.objects.annotate(plant_id=F('meter__metertypeidentifier__plant')) \ .filter(datetime__range=(datetime.datetime(2020,1,1,12),datetime.datetime(2020,1,1,16)), plant_id=2) \ .annotate(date_hour=Trunc('datetime', 'hour')) \ .values('meter', 'date_hour', 'plant_id') \ .annotate(energy_sum=Sum('energy') This expression produces this result: >>> <QuerySet [{'meter': 8, 'plant_id': 2, 'date_hour': datetime.datetime(2020, 1, 1, 12, 0, tzinfo=<UTC>), 'energy_sum': 2253.1499999999996}, {'meter': 31, 'plant_id': 2, 'date_hour': datetime.datetime(2020, 1, 1, 12, 0, tzinfo=<UTC>), 'energy_sum': 3117.9879999999994}, {'meter': 9, 'plant_id': 2, 'date_hour': datetime.datetime(2020, 1, 1, 12, 0, tzinfo=<UTC>), 'energy_sum': 1171.7999999999997}, {'meter': 10, 'plant_id': 2, 'date_hour': datetime.datetime(2020, 1, 1, 12, 0, tzinfo=<UTC>), 'energy_sum': 2441.4749999999995}]> which is not what I expect (the expected result is reported in the table below as the result of the mysql query). Note that readings.query produces the following sql: SELECT "contatoriMisure"."idContatore", "MNContatoriTipi"."idImpianto" AS "plant_id", django_datetime_trunc(\'hour\', "contatoriMisure"."data", \'UTC\', \'UTC\') AS "date_hour", SUM("contatoriMisure"."energia") AS "energy_sum" FROM "contatoriMisure" INNER JOIN "contatori" ON ("contatoriMisure"."idContatore" = "contatori"."ID") LEFT OUTER JOIN "MNContatoriTipi" ON ("contatori"."ID" = "MNContatoriTipi"."idContatore") WHERE ("contatoriMisure"."data" BETWEEN 2020-01-01 12:00:00 AND 2020-01-01 16:00:00 AND "MNContatoriTipi"."idImpianto" = 2) GROUP BY "contatoriMisure"."idContatore", "MNContatoriTipi"."idImpianto", django_datetime_trunc(\'hour\', "contatoriMisure"."data", \'UTC\', \'UTC\') if I change django_datetime_trunc in … -
OTP Verification in Django Rest Framework
I am trying to make a django app in which I want to create a opt verification but I am confused what is the right approach to do it. Here's what I have done so far: Models.py class User(AbstractUser): is_shipper = models.BooleanField(default=False) is_ftlsupp = models.BooleanField(default=False) is_ptlsupp = models.BooleanField(default=False) otp = models.IntegerField(default=1620122) verified = models.BooleanField(default=False) Serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = "__all__" read_only_fields = ('id', 'verified') def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) otp = random_with_N_digits(6) user.otp = otp user.save() subject = 'Please Confirm Your Account' message = 'Your 6 Digit Verification Pin: {}'.format(otp) email_from = '*****' recipient_list = [str(user.email), ] send_mail(subject, message, email_from, recipient_list) return user How can I use this otp to verify the user? My approach is that if the user is created and he tries to login then obviously he is unverified as verified = models.BooleanField(default=False) so he'd be shown a pop up to enter the otp he received on his mail and if the otp matches he can proceed and log-in Views.py To verify otp class verifyOTPView(APIView): def post(self, request): username = request.data["username"] otp = int(request.data["otp"]) user … -
shareable url creation mechanism for current url in Django?
take example : jp having dashboard with some data if i'm shared this page with some person all people can able to see jp dashboard without login authentication https://stackoverflow.com/users/7950598/jayaprakash-k if i'm shared with any persons those persons can able see the jayaprakash profile for this need to create mechanism taking current url as parameter and create one shareable url then if any persons click on shareable url then it will redirect into current url with login middle ware authentication ?? -
Django saves images in two folders
I'm creating a small app as part of my training.This app includes working with images. I don't understand why images saved in "cache" folder in my app. class Post(models.Model): slug = models.SlugField(unique=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') image = models.ImageField(upload_to='posts/') description = models.TextField(blank=True, null=True) users_like = models.ManyToManyField(User, related_name='images_liked', blank=True) created = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.slug: slug = '{}_{}'.format(self.author, timezone.now()) self.slug = slugify(slug) return super(Post, self).save(*args, **kwargs) class Meta: ordering = ('-created',) settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') views.py class PostAddView(LoginRequiredMixin, FormView): form_class = PostAddForm template_name = 'accounts/postForm.html' def form_valid(self, form): post = form.save(commit=False) post.author = self.request.user post.image = self.request.FILES['image'] post.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('account:profile') screenshot -
PayPal Subscriptions Django
I'm trying to implement PayPal subscription functionality into my app and this is where I got so far. I created a function which handles the payment process, and subscribes the user to the selected subscription plan, but I can't figure how can I create similar function for manual subscription canceling? Is that possible? I mean, how can I cancel my subscription as a user? This is my payment process function. def process_order(request, plan_slug): host = request.get_host() plan = Subscription.objects.get(slug__iexact=plan_slug) request.session['plan_id'] = plan.pk order, created = Order.objects.get_or_create( plan=plan, user=request.user, total_cost=plan.sum_price, ) if created: request.session['order_id'] = order.pk elif order: request.session['order_id'] = order.pk order.created = timezone.now() order.save() if plan.slug == 'some_slug': user = Customuser.objects.get(email=request.user.email) user.subscription_plan = plan user.sub_renewal_date = None user.save() messages.success(request, 'You are now some_slug plan!') return redirect('accounts:profile', user.email) paypal_dict = { "cmd": "_xclick-subscriptions", 'business': settings.PAYPAL_RECEIVER_EMAIL, 'a1': 1, 'period1': '1 M', "a3": plan.sum_price, # monthly price "p3": plan.plan_duration, # duration of each unit (depends on unit) "t3": 'M', # duration unit ("M for Month") "src": "1", # make payments recur "sra": "1", # reattempt payment on payment error "no_note": "1", 'item_name': plan_slug, 'item_number': order.pk, 'invoice': str(order.pk), 'custom': { 'order': order.pk, 'user': request.user.email, }, 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('billing:paypal-ipn')), 'return_url': 'http://{}{}'.format(host, reverse('billing:payment_done')), 'cancel_return': … -
Can't save tags in admin using django-taggit
I am using django-taggit and I can't save the tags when creating a new post from the admin panel, when I edit a post I had already created before adding django-taggit, it saves the tags well, what might be the problem? Models.py class BlogPost(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') description = models.CharField(max_length=500) content = RichTextUploadingField(config_name='awesome_ckeditor') tags = TaggableManager() category = models.ForeignKey( 'Category', related_name='category', on_delete=models.CASCADE) cover = models.ImageField(upload_to='images/') created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) #read_time = models.TimeField(null=True, blank=True) status = models.IntegerField(choices=STATUS, default=0) series = models.IntegerField(choices=SERIES, default=0) def __str__(self): return self.title def get_absolute_url(self): return reverse("blog:detail", args=[str(self.slug)]) -
Django elasticsearch DSL DRF suggetions issue
I am implementing Django elasticsearch DSL DRF in my project to create rest API for elasticsearch. Elastic search is working fine but having the issue in search suggestions. As per documentation if I use the suggest in URL then it gives error screen. But I don't add that then I got an incorrect response. I am attaching screenshots of my code. enter image description here enter image description here document code enter image description here view code enter image description here -
How to connect Multiple SAAS apps to work together
we are intending on developing multiple Multitenant SAAS applications (example: Invoicing, HR, Inventory Management). To a point where we want people to pay and buy only the solution they want. I wanted to know what technology to use and how can we connect these applications and their APIs so that they share data with one another so that if someone buys them together they work as one joint suite. -
Testing Image Upload Using Selenium
Im trying to test uploading an image using Selenium. It doesnt throw any errors, but doesn't change the user image (AssertionError: != 'test_img.jpg'). Any help getting this to work would be greatly appreciated. def test_upload_image_works(self): user = User.objects.create(username='testuser', email='user@example.com') self.client.force_login(user) image = SimpleUploadedFile("test_img.jpg", content=open(settings.MEDIA_ROOT+'\profile_pics\\test_img.jpg', 'rb').read(), content_type="image/jpg") self.client.post('/profile/update_profile', {'image': image}) user.refresh_from_db() self.assertEqual(user.profile.image, 'test_img.jpg') Thank you. -
Django template filter to convert a string into single item list
Is there a template filter that converts a string into a list with just one item. I did see make_list but that creates a list of individual characters of the string. Illustration: {{ "string"|filter }} gives ["string"] -
How can send parameter by a tag in django?
I have a 'a tag' such like this. <a href="{% 'mains:index' %}" name="getData">button</a> If I click this button, i want to send parameter name "getData" like below, but it does not work. views.py def index(request): result = request.GET.get('getData') how can I get prameter from template by a tag, and how can using in views.py? return = render(request, 'mains/index.html', 'result':result) if my question is confused, just ask me plz. -
django views count shows 'NoneType' object has no attribute 'comment_set'
''' views.py, I am learning django / python and I am stuck on an issue. shows some error like 'NoneType' object has no attribute 'comment_set', How cna i solve the problem. This is the code for view count. ''' class PostDetail(FormMixin, DetailView): model = BlogSlider template_name = "blogdetails.html" form_class = CommentForm context_object_name = 'detail' def get_success_url(self): return reverse_lazy('blog-details', kwargs={ 'slug':self.object.slug }) def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context['commenting'] = self.object.comment_set.all() context['form'] = self.get_form() context['own'] = BlogSlider.objects.all().exclude(user=self.request.user)[:4] return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.user = self.request.user form.instance.post = self.get_object() form.save() return super(PostDetail, self).form_valid(form) def get_object(self): client = self.request.META['REMOTE_ADDR'] ip = IP() print(client) print(IP) blogview = super(PostDetail, self).get_object() print(str(blogview.ip.all())) if client not in str(blogview.ip.all()): ip.ip_list = client ip.save() blogview.ip.add(ip) blogview.views_count += 1 blogview.save() return blogview