Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
accessing Django user email list
I am trying to create a page for the admin of a website to access to write a message to there email list for registered users on a website. My idea was to create a new form 2 fields: field 1: Subject field 2: message then send a email to all registered users. The part I can't really find much information is how to pass the email list to recipient_list in send_mail(). I am not sure how to access the email list data. I'm using Django/python Any articles on doing this would be appreciated. Thanks -
django multiple file upload (with FOR loop)
I'm looking for method to select and upload multiple files. In Template multiple files are selected but only one uploads. I found this part of code on DjangoProject site def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: ... # Do something with each file. return self.form_valid(form) else: return self.form_invalid(form) What do i have to wright instead "# Do something with each file." to save files? PS: views.py I'm using now for single file upload: def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() form.save_m2m() return redirect('articles:list') else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', { 'form': form }) -
what interesting/essential django packages are you currently using?
state your favorite or useful package for django. django-channels websockset support for asynchronous tasks. -
Code working in django terminal but not in django template
This code below works in the terminal but when I try it in Django templates I get an error (see error below). However this code works just fine in my django terminal >>> for item in order_items: ... if item.reviewed_items.exists(): ... item.reviewed_items.values_list('ratings', flat=True)[0] ... '8' >>> What am I doing wrong {% for item in order_items %} {% if item.reviewed_items.exists %} <span>Your Review</span><br/> <b>{{ item.reviewed_items.values_list('ratings', flat=True) }}/10</b> {% else %} <a href="{% url 'accounts:review' username=item.made_by pk=item.pk %}"> <button class="text-success">Leave Review</button> </a> {% endif %} {% endfor %} Below is the error I am getting TemplateSyntaxError at /order/history/ Could not parse the remainder: '('ratings', flat=True)' from 'item.reviewed_items.values_list('ratings', flat=True)' -
Create a separate clean database for tests in django
Hi I would like to create a separate empty database for tests. I read on django docs (https://docs.djangoproject.com/en/2.1/topics/testing/overview/) that : The default test database names are created by prepending test_ to the value of each NAME in DATABASES. When using SQLite, the tests will use an in-memory database by default (i.e., the database will be created in memory, bypassing the filesystem entirely!). The TEST dictionary in DATABASES offers a number of settings to configure your test database. For example, if you want to use a different database name, specify NAME in the TEST dictionary for any given database in DATABASES. So I tried: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'test_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'), } } but tests still use the default database when running them with ./manage.py test How can I create and specify a new, empty database for tests purposes? -
Django + Heroku: Do automatic migrations need an advisory lock?
I am currently setting up my project via Heroku. I got stuck here where it says: The following considerations are primarily relevant when creating manual database migration scripts. If you are using an ORM, such as ActiveRecord, these considerations may not apply. My question is, do I have to do this when I use Django's command in the RUN command python manage.py migrate? Before running a migration, grab an advisory lock on the database Or is this the ORM case and I don't have to 'grab' this advisory lock. Thank you! -
Problems with converting datetime to string in Django
I can't understand why this isn't working because in a Python console it works fine for me... class Activity(models.Model): id = models.CharField(max_length=250, primary_key=True) description = models.CharField(max_length=255, null=False, help_text="Brief description of the activity") predecessor = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, help_text="Select the activity that takes place prior to this that must be completed before this activity begins.", related_name='dependency') successor = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, help_text="Select the activity that takes place after this that must wait for this activity to be completed before beginning.") servers = models.ManyToManyField('Server') STATUS = ('Not Ready', 'Ready', 'In Progress', 'Fully Completed', 'Partially Completed', 'Cancelled') status = models.CharField(max_length=50, blank=False, default='Not Ready', choices=tuple(zip(STATUS, STATUS))) date_defined = models.DateField(default=timezone.now) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, help_text="The person or group who will be responsible for the completion of this work.") start = models.DateTimeField(default=timezone.now, verbose_name="Planned start date/time", blank=True) end = models.DateTimeField(default=timezone.now, verbose_name="Planned completion date/time", blank=True) CTYPES = ('OS Patching', 'App Config Change', 'Data Load', 'Capacity Change', 'Platform Config Change', 'Other') ctype = models.CharField(max_length=100, verbose_name="Type", default='OS Patching', choices=tuple(zip(CTYPES, CTYPES)), blank=True) contract = models.ForeignKey('Contract', models.CASCADE) detail = models.TextField(max_length=2000, help_text="Provide all necessary details for the work that needs to be performed", blank=True) work_notes = models.TextField(max_length=2000, help_text="Provide all necessary details for the work that needs to be performed", … -
Get model object in category
In my current models. I have 2 models. I have a category and boards model class Categories(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) def __str__(self): return self.name class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) category = models.ForeignKey(Categories, related_name='topics', on_delete=False) I have a for loop displaying all the categories, and I plan to write one to display the boards that belong in that category.But my for loop just displays EVERY board in EVERY category. Where I need the boards where category equals test to display in the category test But Im using boards = Board.objects.all() How would I make it so I only get my for loop would display the board in the correct category? -
django ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
I am getting this error whenever i started the server through manage.py, There is no error in my app or project , I googled the error , but didn't get the satisfied answer, Please tell me what is the reason for below error `ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 500 59 I am not getting this error every time, sometimes i am getting this error , sometimes not. There is a huge stack of error out of i pasted only some lines of error which is the starting point for this error, Please tell how to avoid this type of error. -
Django send progress back to client before request has ended
I am working on an application in Django where there is a feature which lets the user share a download link to a public file. The server downloads the file and processes the information within. This can be a time taking task therefore I want to send periodic feedbacks to the user before operations has completed. For instances, I would like to inform the user that file has downloaded successfully or if some information was missing from one of the record e.t.c. I was thinking that after the client app has sent the upload request, I could get client app to periodically ask the server about the status. But I don't know how can I track the progress a different request.How can I implement this? -
Migration dependencies reference nonexistent When starting a new project
Hi Guys sorry for being so dumb, but i got this problem even after installing django again and starting a new project, have searched online with no avail for a week now. Every time i run migrations this error appears, it is giving me a headache, have tried, python manage.py runserver --fake, have tried removing py files deleting database and so on and failed Here is the error PS C:\Users\Willie\desktop\maoni\maoni> python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", lin e 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", lin e 330, in execute output = self.handle(*args, **options) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\migr ate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", l ine 20, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\loader.py", lin e 52, in __init__ self.build_graph() File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\loader.py", lin e 274, in build_graph raise exc File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\loader.py", lin e 244, in build_graph self.graph.validate_consistency() File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\graph.py", line 261, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\graph.py", line 261, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Willie\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\graph.py", line 104, in raise_error raise … -
Getting values from a queryset getting TypeError: 'method' object is not subscriptable
I know this is a very simple question but I am hitting TypeError: 'method' object is not subscriptable on everything I am trying. I need to get the ratings for the item. How do I get it >>> for item in order_items: ... if item.reviewed_items.exists(): ... print( item.reviewed_items.values()) ... <QuerySet [{' id': 1, 'review_from_id': 5, 'review_for_id': 1, 'ratings': '8'}]> >>> -
django Forms Html Fill form reference
At the moment I have this form: class simpleform(forms.Form): Accountname=forms.CharField(max_length=30) Price=forms.CharField(max_length=30) views working fine: form=simpleform(request.POST or None) if form.is_valid(): /'Do an action/ return redirect('/someurl') and html: <form action="{% url 'someurl' %}" method="POST">{%csrf_token%} <div id="myForm">{{form}}</div> <input class="btn btn-success" type='submit' value='Confirm'/> </form> every thing is fine I got the form that I want i am wondering how can I pass a 'Accountname' already inside 'Accountname' with out showing it as an option -
Django: redirect user to provide more information and on success redirect to previous URL
I know that I can use decorators such as @login_required and @permission_required() or enclose a view in a function like login_required() to redirect a user to sort of provide more information (log in in that case). On success the user is redirected to the URL he was trying to access in the first place (automatically using the logic ?next=/ in the URL). Now I would like to apply the ?next=/ logic to another case. My user is logged in and wants to claim a piece on the website. To successfully do this he must have provided his address. In the view I check if the fields are not empty. If one of the fields is empty I redirect the user to a default UpdateView. If the user filled in the fields (clicks the submit button) I would like to sort of re-run the URL he tried to access before. How does the ?next=/ logic apply in such a case? views.py def claim(request, pk): claimant = Creator.objects.get(user=request.user) if claimant.first_name != None and claimant.last_name != None and claimant.street != None and claimant.street_number != None and claimant.zip_code != None and claimant.location != None and claimant.state_province != None:: piece_instance = PieceInstance.objects.get(pk=pk) piece_instance.claimant = request.user … -
How Filter Objects what contains in FK?
I have three Models, like Store, ProductsArea and Item. A Store can have many ProductsArea, and ProductsArea can have many Items. #models.py class Store(models.Model): name = models.CharField(max_length=64, unique=True) description = models.TextField(null=True, blank=True) class ProductArea(models.Model): store = models.ForeignKey(Store, related_name='productarea', on_delete=models.CASCADE) name = models.CharField(max_length=64,verbose_name=_('Name')) class Item(models.Model): product_area = models.ForeignKey(ProductArea, related_name='items', on_delete=models.CASCADE, verbose_name='Menu') name = models.CharField(max_length=64, verbose_name=_('Name')) price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=_('Price')) In my view I'm using CBV, and I want return all Items what contains the same ProductArea, clicking ListItems from determined ProductArea, with FK they get all items from ProductArea. The same for ProductArea in Store. Store - Clothes Store Product Area - Shirts, Pants Item - Shirt Yellow(PA.Shirts), Shirt Blue(PA.Shirts) Item - Pant Black(PA.Pants), Pants Red(PA.Pants) If a click in Shirts, I want return a list with a Shirt Yellow and a Shirt Blue. I tried this in my view : def get_queryset(self): product_area_id = ProductArea.objects.get(id) product_area = ProductArea.objects.get(pk=product_area_id) items_in_productarea = Item.objects.filter(product_area=product_area) return items_in_productarea But doesn't work,have builtin_function_or_method' object is not iterable Can anyone help me? Thanks a lof friends. -
ManyToManyField show's all the instances instead of related
My models: class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) item_price = models.DecimalField(max_digits=9, decimal_places=2,default=0.00) class Cart(models.Model): items = models.ManyToManyField(CartItem, blank=True) total = models.DecimalField(max_digits=9, decimal_places=2,default=0.00) When I add CartItem instance to a cart and then look at the Cart instance in admin dashboard, I see all the CartItem instances instead of the one's I added to the cart. How do I fix it? -
Prevent m2m_changed from updating date modified of parent class
I have a class called Outfit and within the class, a many to many relationship called Products like this: class Outfit(models.Model): products = models.ManyToManyField(Product, related_name='outfits', blank=True) modified = models.DateTimeField() I have a variable called product_outfit_count in the products model which basically tracks how many outfits a particular product is used in. When an outfit is saved, this signal is called: m2m_changed.connect(update_product_outfit_count, sender=Outfit.products.through) The problem is, when a product's outfit count is updated, the date modified of the outfit changes as well. How can I prevent this? -
Don't have access to all of my static files in Django
So, I'm deploying a Django project at PythonAnywhere, using django-tinymce/django-summernote (I've tried both, and get the same error). Everything works as it should locally, but at PythonAnywhere I don't get the rich-text editor I'm supposed to. I pull up the JavaScript console and noticing a couple of 404 errors. I try to navigate to my static files manually by typing domain.com/static/summernote/summernote.css in my URL field and gets the following 404 error: Using the URLconf defined in Domain.urls, Django tried these URL patterns, in this order: 1. ^$ [name='article_list'] 2. ^posts/(?P<pk>\d+) [name='post_detail'] 3. ^search$ [name='search_result'] 4. ^summernote/ 5. ^media\/(?P<path>.*)$ 6. ^admin/ The current path, static/summernote/summernote.css, didn't match any of these. However, when I enter the path to my other CSS or JS files (Which is in the same static directory), the file shows up. Also, entering the path locally (http://127.0.0.1:8000/static/summernote/summernote.css) workes fine. So now I really don't know what to do. Any ideas? -
google SMTP email sending not working python
I am trying to learn how to send emails using google smtp. I am just trying to verify that I am able to send emails. They way I want it to work is when a user registers to my site it will automatically send an email to them saying "thanks for registering..." settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com.' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'pw' views.py (only showing register) from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth import logout, authenticate, login from django.contrib.auth.forms import UserCreationForm from .forms import RegisterForm from django.core.mail import EmailMessage, send_mail from django.conf import settings def register(request): """" Register a new user. """ if request.method != 'POST': # Display blank registration form form = RegisterForm() else: # Process completed form. form = RegisterForm(data=request.POST) new_user = form.save() # Log the user in then redirect to home page. authenticated_user = authenticate( username=new_user.username, password=request.POST['password1']) login(request, authenticated_user) return HttpResponseRedirect(reverse('blogging_logs:index')) subject = "Thank you for registering to blogging site." from_email = settings.EMAIL_HOST_USER to_email = ['sending_to@gmail.com'] body = "Thanks for registering to the website let me know what you think" send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=body, fail_silently=False) context = {'form': form} return render(request, … -
How to display choices as checkboxes in django?
I have a model which i am overriding in forms.py and displaying in frontend. So choices field is coming as drop down but i want it to render as checkbox, i tried to do so by overriding in form with forms.CheckBoxInput() but its just showing checkbox for region hot for its respective options.so can please guide me how to achieve it. models.py region_choices = ( ('AF', 'Africa'), ('AS', 'Asia'), ('EU', 'Europe'), ('NA', 'North America'), ('SA', 'South America'), ('OC', 'Oceania'), ('AN', 'Antarctica'), ) class Registeration(models.Model): username = models.CharField(max_length=100) email = models.EmailField() password = models.CharField(max_length=100) confirm_pasword = models.CharField(max_length=100) region = models.CharField(choices=region_choices,max_length=10) terms_confirmed = models.BooleanField(default=False) def __str__(self): return self.username forms.py class RegistrationForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(RegistrationForm,self).__init__(*args,**kwargs) self.fields['region'].widget = forms.CheckboxInput() class Meta: model = Registeration fields = '__all__' html <form> {% csrf_token %} {{form.as_p}} <input type="submit" value="ok"> </form> -
Django low query speed for "checking if OneToOneField is None"
class ArticleText(models.Model): article = models.OneToOneField(Article, on_delete=models.CASCADE, related_name="article_text") text = models.TextField() indexed_by_es = models.BooleanField(default=False, db_index=True) indexed_by_solr = models.BooleanField(default=False, db_index=True) -
get request context in Advanced custom template tags¶
in Django, simple and inclusion template tags allows getting the request context with @register.simple_tag(takes_context=True) https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags however, for custom tags, I don't see how this is done. What I am trying to do is extend the i18n {%trans%} tag, to look for translation in the Database first, before using gettext, I need access to the request.Language from the custom template tag. -
Creating model in task leads cannot connect to postgres database - tries to use socket instead of network port
I am at wits end. I researched for sometime, and maybe I don't know the correct keywords, but I couldn't find a solution that worked. I have dockerized a Django app (custom link shortener) with a Postgres backend that uses Celery, RabbitMQ for a single task - to create and save an object to the database when a GET request is made. The idea is this: when a shortlink is requested (GET request), the app simply redirects the request to another URL, but also creates a task using Celery. That task is supposed to add an analytics record to the Postgres database. The redirect works fine. I can create new shortlinks just fine. The django app connects to the postgres container fine. But Celery, in a different container tries to connect upon creating and saving the new object to the postgres container via a socket. This is the main error: celery | django.db.utils.OperationalError: could not connect to server: No such file or directory celery | Is the server running locally and accepting celery | connections on Unix domain socket "/tmp/.s.PGSQL.5432"? The following are what I think is the relevant, code, but if I didn't include something, please let me know. … -
AttributeError: 'tuple' object has no attribute 'get_extra_actions' with function based view in Django Rest Framework
I have created a function based view since it does not require model queryset directly. graph_data/views.py @api_view(http_method_names=['GET']) def my_func(request): print(request) return Response({'message': 'success'}) And in the graph_data/urls.py from django.urls import path from graph_data.views import my_func app_name = 'graph_data' urlpatterns = [ path('my_func/<contact_id>', my_func, name='my_func') ] and included graph url in main app urls.py router = routers.SimpleRouter() router.register(r'graph/', include('graph_data.urls'), base_name='graph_data') urlpatterns = [ path('', include(router.urls)) ] But this gives AttributeError: 'tuple' object has no attribute 'get_extra_actions' -
Django - is there better way to get data from forms field?
Is there a better way(easiest and safest) to retreive data from input fields that has been created in form.Form than request.POST.get()? For practice purpose I have 2 pages: I enter some data I use data from 1st page this is my solution: form.py: class DataForm(forms.Form): login = forms.CharField(label='login') password = forms.CharField(widget=forms.PasswordInput) def clean_data(self): login = self.request.POST.get('login') return login views.py: class MyTestView(FormView): template_name = 'template.html' form_class = DataForm success_url = '/finaldestination/' def form_valid(self,form): form.clean_data() return super().form_valid(form) def testFunction(request): print('Welcome here') testprint() form = DataForm(request.POST or None) testFunction.login = request.POST.get('login') testFunction.password = request.POST.get('password') importedScript.login(testFunction.login, testFunction.password) tested() print(form.Login) return render(request, 'finaldestination.html') def tested(): x = testFunction.login print(x, ', is a really cool guy') template.html: TEST: <form action="/finaldestination/" method="post" name='btn'> {% csrf_token %} {{ form.login }} {{ form.password }} <input type="submit" value="Submit"> </form> ImportedScript.bot is a simple code to login to Instagram. My solution is working but I have heard that it is not a safest way to retreive data. As I wrote at the beginning it is for practice purpose because I still do not understand how to use the data entered by the user. For example I would like to create a loan calculator where user has to put a lot of …