Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to keep adding divs while there are objects to loop in Django?
I am creating a blog homepage. I basically have two divs. One the first one I only want to show the latest post added. On the second I want to show all other posts. So, I created this template: <div class="row"> {% for post in post_list %} {% if forloop.counter == 1 %} <div class="col-lg-10 mx-auto"> <div class="card card-blog card-background"> <div class="full-background" style="background-image: url('{{post.image.url}}"></div> <a href="{% url 'post_detail' post.slug %}"> <div class="card-body"> <div class="content-bottom"> <h6 class="card-category text-white opacity-8">{{post.created_on}}</h6> <h5 class="card-title">{{post.title}}</h5> </div> </div> </a> </div> </div> </div> <div class="row justify-content-center"> {% else %} <div class="col-lg-5"> <div class="card card-blog card-background"> <div class="full-background" style="background-image: url('{{post.image.url}}')"></div> <a href="{% url 'post_detail' post.slug %}"> <div class="card-body"> <div class="content-bottom"> <h6 class="card-category text-white opacity-8">{{post.created_on}}</h6> <h5 class="card-title">{{post.title}}</h5> </div> </div> </a> </div> </div> {% endif %} {% endfor %} My problem is that, right, after the {% else %}, it will loop two posts and stop. How can I make it continue to loop as long as there are posts? -
How to style TextField() model in django
I have got a field in my table: description = models.TextField() I would like to be able to decide how the text is display. For example I have a main description of a product and then I want to display some information like that: data1: data1 data2: data2 When I am adding a description in django admin page everything is connected with each other data1: data1 data2: data2 Is there a way to organize it in a different way? Can I choose what text would be bold? -
How do I form a Django query with an arbitrary number of OR clauses?
I'm using Django 2.0 with Python 3.7. I want to write a query that returns results if the fields contains at least one of the strings in an array, so I want to set up an OR query. I have tried this class CoopManager(models.Manager): ... # Meant to look up coops case-insensitively by part of a type def contains_type(self, types_arr): queryset = Coop.objects.all() for type in types_arr: queryset = queryset.filter(type__name__icontains=type) print(queryset.query) return queryset However, this produces a query that ANDs the clauses together. How do I perform the above but join all the clauses with an OR instead of an AND? I'm using MySql 5.7 but I'd like to know a db independent solution if one exists. -
How to improve problem solving skills in python/Django
I can say I am an intermediate programmer in python Django. I am trying to find a website (documents; anything) which hosts good puzzles (or similar) for python. My objective is to experience mind teasers kind of things for python. And certainly not any interview kind of questions. I would want to improve my techniques in python/Django, during a situation to solve a problem, or during implementation of an algorithm, etc. Second, I am also looking into new, simple and innovative problems (just problems, to improve problem solving) which can be practiced in python. For example, implementing shift rotate functionality (this is very basic, but will teach you in-depth bit handling), and to a advanced level like graphs; etc. -
Reset password after first successful login in Django python
I am building an web application using existing Auth features in Django where admin create user profile with username and password. Admin created user name and password will be given to user to login. So for security reasons I need to ask user to reset password (given by admin) after user's first successful login. To reset password, I will be displaying template where user should be entering only new password and new password again for confirmation. This new password will be updated in sqlite database. So whenever admin changes the users password. I need to ask users to reset password after first successful login. I know this if off topic for stacoverflow and for reasons I couldnt post a question in StackExchange. Please refer me or help will be appreciated. -
How to Setup Divio CLI using WSL 2 for Windows 10?
So I just tried to setup Divio CLI via WSL 2 Terminal. My WSL 2 setup I'm using is based on Ubuntu 18.04.4 LTS, bionic. So everything was working well initially: I typed divio login and add my access token in the CLI, worked well. Then, I typed divio doctor, all checks out: Login, Git, Docker Client, Docker Machine (I installed it separately via the WSL terminal), Docker Compose, Docker Engine Connectivity, Docker Engine Internet Connectivity, and Docker Engine DNS Connectivity until I typed this command divio -d project setup sample-djangocms-project and got this error: Error: Resource not found. You are logged in as '#########@#####.com', please check if you have permissions to access the ressource Can someone tell me why this happened? I am kinda stuck. And what should I do next? -
User provided email over the landing page is not showing in the database in Django
I am trying to put a subscribe email form on my landing page, however, I am not able to see the input email addresses on my admin(backend). Why it's not writing user-provided email input to my database? base.html <form method="post" > {% csrf_token %} <label >Your Email: </label> <input type="text"> <input type="submit" value="Submit"> </form> models.py from django.db import models from django.urls import reverse # Create your models here. class EmailSubmit(models.Model): email_name=models.EmailField(max_length=30) forms.py from django import forms from .models import EmailSubmit class EmailForm(forms.ModelForm): class Meta: model=EmailSubmit fields=[ 'email_name', ] views.py from django.shortcuts import render from .forms import EmailForm def index(request): return render(request, 'base.html') def email_post(request): form = EmialForm(request.POST or None) if form.is_valid(): form.save() context={ 'form':form } return render(request, 'base.html', {'form': form}) so when the user puts the email and submit, the page refreshes but nothing shows up on the backend. What is wrong with my code here? -
AJAX form submission to Django Class View
I'm trying to submit data to model using Ajax, its gives a 403 (Forbidden), view I'm using is a Class View. Things works fine without Ajax. How to do the same with ajax ? My Url : path('add_to_cart/<slug>', views.AddToCartView.as_view(), name='add_to_cart'), My View : class AddToCartView(LoginRequiredMixin, View): model = Wishlist @method_decorator(csrf_exempt) def get(self, request, *args, **kwargs): print(self.request.user) print(self.kwargs['slug']) wished_product = get_object_or_404(Product, slug=self.kwargs['slug']) product,created = self.model.objects.get_or_create(product=wished_product, customer = self.request.user) return HttpResponse(status=201) and ajax call $('.buy').click(function(e){ e.preventDefault(); let _this = $(this); var slug = _this.data('id'); $.ajax({ type : 'POST', url : 'add_to_cart/'+ slug +'/', success: function(data){ if(data.success = true){ _this.addClass('clicked'); } }, async : false, error : function(data){ alert(data); } }) }); When i use 'POST' instead of 'GET' in Ajax type it gives 404 (Not Found) -
WebSocket server refusing all connections in Django Channels
I was doing a chat with django (backend) and react (frontend). I use Django Channels to create the WebSocket server, but it isn't working : when trying to connect with React, it throws Forums.jsx:61 WebSocket connection to 'ws://localhost:8000/forums/divers/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET in the navigator console. This morning it was working, but this afternoon, after having closed and reopened the 2 servers, it isn't working. I only started a system to store the messages in the database during this time. The consumer: from channels.generic.websocket import WebsocketConsumer import json from .models import Message class ChatConsumer(WebsocketConsumer): async def connect(self): self.forum = self.scope["url_route"]["kwargs"]["forum"] # Join room group await self.channel_layer.group_add( self.forum, self.channel_name ) print("connect func") self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.forum, self.channel_name ) async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] print(message) await self.channel_layer.group_send( self.forum, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): message = event['message'] #await sync_to_async(Message.objects.create)(message=message["message"], ) # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) opening of WebSocket client: class Forum extends Component { constructor(props) { super(props) ... this.URL = constants.BACKEND_WS + "/forums/" + this.state.forum + "/"; this.ws = new WebSocket(this.URL) } componentDidMount() { console.log("didmount"); this.ws.onopen = () => { … -
One to One vs field in same models django
I have created two templates I have the extended template De user (AbsctractUser) and the template (Score) with the field total_score. From what I could understand about the django cache with redis is that as long as the line is not modified, redis keeps the information in cache. The total_score field will be updated regularly, like 100 times every 10 minutes if it is added in the AbstractUser template, this one will force redis to regularly update the user's cache at each page change (view), whereas if I create a second Score template with a OnetoOne relationship, this one will be updated only on the 2 pages concerned or the view loads the Score model. Or I can put directly the field total_score in my abstract user and update it regularly. But for me I lose the efficiency of redis for the Abstract User model. I'd like to know if my reasoning is correct... What I could read is that a OnetoOne is useful to extend an already existing table, but for the creation of a new project it is necessary to avoid the OnetoOne, and to add directly the field in the model. so I'm in a fog. Thank … -
custom.methods.wrap didn't return an HttpResponse object. It returned None instead
What's wrong in my code.. ? I'm returning an HttpResponse conditionally, yet I keep getting an error decorators.py def has_permission_view(): def decorator(view_func): def wrap(request, *args, **kwargs): if request.user.role == 'admin': if not hasattr(request.user, 'institute'): messages.add_message( request, messages.WARNING, "Please Add Your Institute Information") return HttpResponseRedirect(reverse('accounts:add_institute')) elif not hasattr(request.user.institute, 'device'): messages.add_message( request, messages.WARNING, "Please Add Your Attendance Device Information") return HttpResponseRedirect(reverse('accounts:device')) elif request.user.role == 'employee': return HttpResponseRedirect(reverse('accounts:profile')) return wrap return decorator views.py @login_required @has_permission_view() def index(request): context = {} d = request.user.institute.device zk = ZK(d.ip, d.port, timeout=5, password=0, force_udp=False, ommit_ping=False) try: conn = zk.connect() context['object'] = conn except Exception as e: messages.add_message(request, messages.WARNING, e) return render(request, 'index.html', context) I Got This Error Message The view custom.methods.wrap didn't return an HttpResponse object. It returned None instead. -
Can I do work after the Django request cycle?
I have a SLO to return responses from my django app in 3 seconds, but occasionally the work that I'm doing within a request takes longer than this. The extra work can be done asynchronously, so I'm looking into celery. BUT, the work logically belongs with the request and it would be nice if I didn't have to go to all the extra work of setting up a celery queue. I don't have much traffic and I don't mind taking up just a little more time with my uwsgi worker. Is there any condoned way (or perhaps even un-condoned way) to do work after the response has been returned but before leaving the request cycle? -
Django - exclude elasticsearch objects from search view on bool change
I want to exclude specific elements out of my (elastic)search results view. Imagin you have a onlineshop only with unique items out of diffrent models which getting sold and if smb. buys the object the sold boolan field changes to true at the database. At the moment the objects becomes sold it should get excluded from the search results. this is how far a came till now but I dont know how I can filter e.g. "z = ZDocument" for the field "sold" and only show objects where sold=False views.py example def search(request): if request.method == "GET": searchquery = request.GET.get('searchquery') page = request.GET.get('page') if searchquery: x = XDocument.search().query("multi_match", query=searchquery, fields=["title", "content", "tag"]).to_queryset() y = YDocument.search().query("multi_match", query=searchquery, fields=["title", "content", "tag"]).to_queryset() z = ZDocument.search().query("multi_match", query=searchquery, fields=["title", "content", "tag"]).to_queryset() searchquery = list( sorted( chain(x, y, z), key=lambda objects: objects.pk )) else: searchquery = '' ... return render... thanks for reading -
Django, how do i compare leftovers
I have two models, warehouse and products. Subcategories are Hotdog value and There are two values in the warehouse, sausage and bun, I indicated the quantity to them I connected them using ManyToMany, now I need to make it show how many pieces there are. Example models.py class Stock(models.Model): title = models.CharField(max_length=255) limit = models.IntegerField() def __str__(self): return self.title class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=255) price = models.IntegerField() stock = models.ManyToManyField(Stock) def __str__(self): return self.title views.py {% for item in subcategories %} <a href="#" class="c-item"> <h2>{{ item.title }}</h2> <h4> {{ item.price }} сом <span class="badge badge-danger">20 pieces</span> </h4> </a> {% endfor %} -
Why does this API request work in Postman but it raises an error in Django test?
I post to my API to create an account from Postman { "email": "snifter@gmail.com", "display_name": "outrageous canteloupe", "password": "GramDaddyff!!5" } It works, and a new account is registered in the databse. Then I try to make the same request from a Django test. class AccountAPITestCase(TestCase): def setUp(self): pass def test_create_account(self): c = Client() response = c.post('/accounts/', { "email": "snifter@gmail.com", "display_name": "outrageous canteloupe", "password": "GramDaddyff!!5", }) account = Account.objects.get(display_name='big_ouch') self.assertTrue(account) And I get the following error. ====================================================================== ERROR: test_create_account (accounts.tests.AccountAPITestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/mcm66103/Documents/python/photo-contest-BE/accounts/tests.py", line 28, in test_create_account "password": "use_in_migrationsDaddyff!!5", File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/test/client.py", line 526, in post response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/test/client.py", line 356, in post secure=secure, **extra) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/test/client.py", line 421, in generic return self.request(**r) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/test/client.py", line 496, in request raise exc_value File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/rest_framework/views.py", line 476, in … -
Unrecognized day of week error in python-Cron tab
I am working on a Django app. I was using crontab for jobs in background. Here is an example of my code from crontab import cronTab pddays=[1,2,3,4] cron = CronTab(user=username) job = cron.new(command=“curl http://***********”) job.dow.on(str(pddays)[1:-1]) cron.write() But when I execute it I get the error - ValueError: Unrecognized Day off week ‘1,2,3,4’ -
Can't show variables inside Django blocks
I have a simple parent template like this that uses Django blocks //base.html <!doctype html> <body> {% block content %} {% endblock %} </body> </html> But whenever I try to print the variables passed by views.py inside the block nothing is neither displayed nor received, when I put all the html code together in a single file without a parent template it works perfect. This is the basic idea of the block //block.html {% extends 'folder/base.html'%} {% block content %} <h1> {{data}} </h1> {% endblock %} And this is the content of the views.py function: def function(request): return render(request,'folder/block.html',{'data':'someRandomString'}) -
Django signals not working inspite of putting everything in place
My Case In my case User is the default django user model and I've created a Profile to add more details to the User model. To achieve Now what i want is that whenever I create a new User a Profile for that user should automatically get created. I've done I have checked my signals.py file and also imported the signals in apps.py file but still nw Profile is not being created for each new user being created :( Code below I have provided the code in my signals.py and apps.py file below. Please ask me if you need some more code and thanks in advance :) Here is my signals.py file #This is the signal that will be sent from django.db.models.signals import post_save #This is the object which will send the signal from django.contrib.auth.models import User #This will receive the signal from django.dispatch import receiver #We need this to perform operations on profiles table from .models import Profile #This function creates new profile for each user created @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) #This function saves those newly created profiles @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() Here is my apps.py file from django.apps import … -
Is there a way reach to grandchild count with related name in django?
I have several models like that; class Survey(models.Model): name = models.CharField(max_length=200, null=False) class SurveyCollector(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE, related_name='survey_collector_survey') class SurveyResponse(models.Model): collector = models.ForeignKey(SurveyCollector, on_delete=models.CASCADE, related_name='surveyresponse_collector') and i would like to display survey responses count in the survey_list.html. My template code seems like that; {% for survey in surveys %} <tr> <th scope="row">{{ survey.name }}</th> <td align="center">{{ survey.survey_collector_survey.count }}</td> </tr> {% endfor %} I can get surveys collectors with above code. But i cannot get true result when i try this code <td align="center">{{ survey.survey_collector_survey.surveyresponse_collector.count }}</td> I couldnt find right approach. Could you please help me to find the best way? -
How make registration and log in option for Django API without the use of forms/HTML?
I have made an API using Django that displays school subjects for student. I wish to modify this API in such a way that student can only view the modules/data if they are logged in to the API. The API has no front-end/html/css. How can I make a registration option that does not require a html form but can simply read JSON data provided by a POST request from a client (For example "Postman"). Where the POST request for registration would be sent to localhost:test/register and would contain something like: {"username":"...","password1":"...","password2":"..."} and the POST request for log in would be sent to localhost:test/login and would contain something like: {"username":"...","password":"..."} -
Filter items according to Foreign Key
I have a model called Destination, each Destination has it's own certain Bucket Lists (DestinationBucketlist model) related to that Destination. What I want to do is in Bucket List Detail page show the list of related Bucket List items belonging for the same Destination. In other words I want to filter them according to the Destination. I tried multiple examples, but the problem is that either I get the list of all existing Bucket List items despite the Destination or it shows nothing... I think there should be something in my views.py but I can't figure out what I am missing. Here is bit of my code models.py: class Destination(models.Model): destination = models.CharField(max_length=200) description = RichTextField() main_photo = models.ImageField(blank=True, null=True) tags = TaggableManager() def get_absolute_url(self): return reverse("destination_detail", kwargs={'pk': self.pk}) def __str__(self): return self.destination class DestinationBucketList(models.Model): place_name = models.CharField(max_length=200) photo = models.ImageField(blank=True, null=True) description = RichTextUploadingField(blank=True, null=True) tips_desc = RichTextUploadingField(blank=True, null=True) description2 = RichTextUploadingField(blank=True, null=True) destination = models.ForeignKey(Destination, related_name="destination_bucketlist", on_delete=models.CASCADE) views.py: class DestinationDetailView(DetailView): model = Destination template_name ='WSE_blog/destination_detail.html' context_object_name = 'destination' def get_context_data(self, **kwargs): context = super(DestinationDetailView, self).get_context_data(**kwargs) context['destination'] = self.object context['post'] = self.object context['destinations_list'] = DestinationList.objects.all() context['destinations_detail'] = DestinationDetail.objects.filter(destination=self.object) context['bucket_list'] = DestinationBucketList.objects.filter(destination=self.object) context['related_articles'] = self.object.tags.similar_objects()[:4] return context class BucketlistDetailView(DetailView): model … -
Django project run broker and woker in remote host
I have a Django project, and it runs celery using Rabbitmq as a broker in a remote server. I wonder if I can run worker on the remote server too. I do not want to run broker and worker in one remote server, but run it on seperated remote server. I wonder if this is possible. -
Django. Where to put custom methods in models.py?
I put some logic into custom methods in my model. I did it for using those methods in views My model: class Quiz(models.Model): # Some fields.. # And some example methods that contain a logic def get_manage_questions_url(self): return reverse('manage-questions', kwargs={'slug': self.slug}) def get_likes_count(self): return self.likes.count() def get_completed_count(self): return QuizManager.objects.filter(quiz=self, completed=True).count() def like_quiz(self, quiz, user): data = {} if user in quiz.likes.all(): quiz.likes.remove(user) data['liked'] = False else: quiz.likes.add(user) data['liked'] = True data['likes'] = quiz.get_likes_count() return data def increase_views(self): self.views += 1 self.save(update_fields=('views',)) I have a question: Do I need to write all custom methods in the model or I need to put methods like these into a manager kind of QuizManager(models.Manager) and define "objects" attribute in the quiz model? -
Django: Model class __main__.Source doesn't declare an explicit app_label when loading a model in PyCharm
I used to load models in Python shell in PyCharm with no error before, but now it through this error Traceback (most recent call last): File "<input>", line 12, in <module> File "C:\...\lib\site-packages\django\db\models\base.py", line 112, in __new__ raise RuntimeError( RuntimeError: Model class __main__.Source doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I checked similar questions such as this and this and followed the proposed answers with no success. Funny thing is that python manage.py runserver doesn't through any error and website load smoothly. The only change to my environment is that update for windows I got yesterday. I already have app name for all of my apps, set the DJANGO_SETTINGS_MODULE and all imports are absolute. -
Testing Django Activation email with selenium / pytest. EMAIL_BACKEND="django.core.mail.backends.filebased.EmailBackend"
I'm trying to write a function that tests activation email send by selenium Firefox client. Activation Emails are successfully written as files under "tests/test_selenium/outbox" directory, but I"m not able to handle email in test_activation_email() method. Django==2.2 pytest-django==3.8.0 settings.py EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = os.path.join(BASE_DIR, "tests", "test_selenium", "outbox") test_registration.py import pytest, time, os from django.core import mail from src import settings from yaml import safe_load from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities # firefox driver from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from selenium.webdriver.firefox.firefox_binary import FirefoxBinary @pytest.mark.django_db(transaction=True) class TestCreateAccount(): t_username = "Pesho" t_password = "alabala" t_perm_email_1 = "pesho@example.com" t_perm_email_2 = "pesho@example.com" t_denied_email = "pesho@gmail.com" def setup_method(self, method): # Load config and check/download browser driver config_file = 'tests/test_selenium/selenium_config.yml' with open(config_file) as ymlfile: cfg = safe_load(ymlfile) # Firefox headless option options = Options() if cfg['HEADLESS_BROWSER']: options.headless=True if cfg['BROWSER'].lower() == 'firefox': # check if driver is downloaded try: if os.path.isfile(cfg['SELENIUM_DRIVER_FF_BIN']): print(f"Driver {cfg['SELENIUM_DRIVER_FF_BIN']} found") except Exception as e: raise(f'Driver not found: {e} run selenium_downloader.py first') self.driver = webdriver.Firefox( options=options, # firefox_profile = ff_profile, # capabilities=firefox_capabilities, # firefox_binary=binary, executable_path=cfg['SELENIUM_DRIVER_FF_BIN']) elif cfg['BROWSER'].lower() == …