Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Django doesn't want to create startapp?
msinfo32@dEfaaPc2:~/Django/malybar$ python manage.py startapp testApp1 Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? What i should to do? -
Receiving a list of related models from the list of objects (bound by a foreign key). Django
I have two very simple classes for products and photos. I would like to present products on the main page of my store along with photos related to a foreign key. But I do not know how to do this, I found many answers to get this in the view using a join like 'prefetch_related' but my ID changes for each case. So how do you present your photos for each product? are there any Django tags about which I do not know? my models.py class Product(models.Model) name = models.CharField(max_length=10) class Image(models.Model) image = models.ImageField() name_related = models.ForeignKay(Product, on_delate=models.CASCADE) views.py def home(request): product_list = Product.objects.all()[:12] #img = ?? context = {'product_list': product_list, } return render(request, 'home.html', context) Any help will be appreciated. -
Making use of the users table, causing an error
In Django (2.x) I have an entry form, the model is here: from django.db import models from django.contrib.auth.models import User from django.conf import settings class Sample(models.Model): sample_id = models.AutoField(primary_key=True) area_easting = models.IntegerField() area_northing = models.IntegerField() context_number = models.IntegerField() sample_number = models.IntegerField() # taken_by = models.IntegerField() taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.PROTECT) def __str__(self): return str(self.sample_id) class Meta: db_table = 'samples\".\"sample' #ordering = ["sample_id"] managed = False #verbose_name_plural = "samples" This works as expected, a list of usernames drops down (while I would like to format - firstname lastname). However, when I return to the main viewing page I see an error. django.db.utils.ProgrammingError: column sample.taken_by_id does not exist LINE 1: ...text_number", "samples"."sample"."sample_number", "samples".... ^ HINT: Perhaps you meant to reference the column "sample.taken_by". Clearly Django is adding the _id to the table name causing the error, I expect because it is a foreign key. Any ideas how to remedy this behaviour? -
How can I send emails in Django using smtp.EmailBackend without authenticating with the mail server
Is there a way to explicitly tell Django not to authenticate with the mail server when sending the emails. I am currently using the following settings in my settings.py for sending emails. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'my-mail-server' EMAIL_PORT = 25 Please not that I have no EMAIL_HOST_USER and EMAIL_HOST_PASSWORD and the smtp mail server I am using doesn't require clients to authenticate Edit: When I use those settings I get this error smtp.SMTPSenderRefused: Client was not authenticated -
Rendering an XML value to HTML within Python-Django project
I am trying to render a value within an XML file to a HTML page so that is renders in the browser. The value that I want to display is the version number of my project and is in the format "v2.0.0". This XML file is named 'build.xml' and is contained with the 'templates/' folder in my Python=Django project. The problem I am having is that my Python code just opens the XML file when I hit the index "/" page. I want the value to be passed to the HTML. File: myproject/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] File: myproject/views.py from django.http import HttpResponse def index(request): #return HttpResponse('Hello, welcome to the index page.') return HttpResponse(open('templates/build.xml').read(), content_type='text/xml') File: myproject/templates/build.xml <version>v2.0.0</version> -
Making many-to-many relationships with different price for different customer
I have three models Product, Buyer, Offer. Any buyer can inquire me with any kind of Product but for each customer I might offer different price. net price of product is already given by supplier. I wrote the code below and suddenly realized I can only select products for a offersheet but cannot give different price everytime for each product and for each customer with this code. It would be nice if anyone could give me some suggestions. Thanks. class Product(models.Model): name = models.CharField(...) net_price = models.NumericField(...) class Buyer(models.Model): name = models.CharField(...) class Offer(models.Model): date = models.DateTimeField(auto_created=True, auto_now_add=True) buyer = models.ForeignKey(Buyer, default='',) products = models.ManyToManyField(Product, related_name='offer',) -
How to set up FilePond js image preview
I am trying to use FilePond to allow users to upload drag and drop images. I've set up the FilePond drag and drop and I'm trying to implement the image preview feature. I've attached the css and js and included it in my html. The image preview still isn't working. {% extends 'main/dashboardbase.html'%} {% block content %} {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-tofit=no"> <link rel="stylesheet "type="text/css" href="{% static 'main/add.css'%}"> <link rel="stylesheet "type="text/css" href="{% static 'main/filepond.css'%}"> <link rel="stylesheet" type="text/css" href="{% static 'main/filepond-plugin-image-preview.css'%}"> </head> <body> <button type="submit" id="add">Save</button> <a href="{% url 'main:products'%}"> <button id="cancel" >Cancel</button> </a> <div class="col-sm-12 col-lg-6" id="inner"> <form method="POST" enctype="multipart/form-data" id="inputform" name="form1"> {% csrf_token %} <h4>Title</h4> <input type="text" name="product_title" id="product_title" placeholder="Give your product a name"> <h4>Price</h4> <input type="text" name="product_price" id="product_price" placeholder="0.00"> <h4>Description</h4> <input type="text" name="product_description" id="product_description" placeholder="Write a description about your product"> <input type="file" name="product_images"> </form> </div> <script type="text/javascript" src="{% static 'main/add.js'%}"></script> <script src="{% static 'main/filepond-plugin-image-preview.js'%}"></script> <script src="{% static 'main/filepond.js'%}"></script> <script> const inputElement = document.querySelector('input[type="file"]'); const pond = FilePond.create(inputElement); FilePond.setOptions({ server: '#' }); </script> </body> </html> {% endblock%} -
Iterate object list with VueJs from Django API
I try to iterate through a Django Rest API object list using VueJS. I can get the articles json list but I can't correctly view VueJs template component. In my Django views I use <section class="blog-post-wrap medium-padding80"> <div class="container"> <div class="row"> <div id="starting"> <article-list></article-list> </div> </div> </div> </section> And I use VueJs component template new Vue.component('article-list', { template: ` <div class="col col-xl-4 col-lg-4 col-md-6 col-sm-12 col-12"> <div class="ui-block" <div class="post-content"> <a href="#" class="post-category bg-blue-light">THE COMMUNITY</a> <a href="#" class="h4 post-title">{{article.title}}! </a> <p>Here’s a photo from last month’s photoshoot. We got really awesome shots for the new catalog.</p> </div> <!-- ... end Post --> </div> </div> `, props: { article: Object } }); I try to use it with my Vue script new Vue({ el: '#starting', template:`<div><article-list v-for="item in articles" :article='item' :key='item.id'></article-list></div>`, delimiters: ['${','}'], data: { articles: [], search: '', loading: false, currentArticle: {}, message: null, newArticle: { 'title': null, 'content': null }, }, mounted: function() { this.getArticles(); }, computed: { filteredArticles:function (){ return this.articles.filter((article) => { return article.title.match(this.search); }); } }, methods: { getArticles: function() { this.loading = true; this.$http.get('/api/articles/') .then((response) => { this.articles = response.data; this.loading = false; }) .catch((err) => { this.loading = false; console.log(err); }) }, } }); … -
Add a time counter in Django model and templates
I'm working on a project using Python(3) and Django(2) in which I need to implement a time counter, the application is actually something like a Freelancing site, in which a user will order a service from a seller and when he makes the order along with the time selection (e.g he selected 5 days) then I want to show a time on the order page and also track this from server side. I couldn't get any idea on how to implement this? It will look like something as below: Is there some suggestions, resources and any idea how can I implement this feature in Django models and templates. -
Unit testing Django settings pulled in from environment variables
I have some code in my Django settings.py file which updates settings based on environment variables, for example: settings.py DEBUG = bool(int(os.environ.get('DEBUG', 0))) I want to test this behaviour, to ensure if the app loads with environment variables DEBUG=1, then settings.DEBUG is set to True. I've tried the following tests: test_settings.py def test_debug_mode(self): """Test that debug mode is False by default""" self.assertFalse(settings.DEBUG) @patch.dict(os.environ, {'DEBUG': '1'}) def test_debug_true_if_env_var_1(self): """Test that debug mode set to true environment variable set""" self.assertTrue(settings.DEBUG) However, every time I run the tests, DEBUG is being set via the environment variables on my system, instead of from the os.environ patch. My guess is the settings.py is loaded before my test function runs, so it's already set. Is there a way I can mock the environment variables on the test function to test my settings.py file? Appreciate any guidance. -
How to integrate Apache Superset with my python script?
I want to use Apache Superset for the Visualisation process in my web app and for that I need to make a call over my Apache Superset running server through my Api server and in response want a particular visualisation link which i can use in to show charts or tables to user. If anyone has use this please respond. Thanks. -
Difference between using 'and' and using '&' in Django ORM
I have Query which shows different results when i use and or & criteria1 = Q(id__gte=802, id__lte=1000) criteria2 = Q(country_id__contains='UK') I always have been using : q = Mymodel.objects.filter(criteria1 & criteria2) But in this particular case when i use & it always outputs a single row . (I also checked print q.query(), query comes out to be fine) However, when i use and instead of &. Query gives correct output q = Mymodel.objects.filter(criteria1 and criteria2) what actually is happening under the hood ? -
How to save Data in database using post in locust load testing tool?
@task(1) def CreateCustomer(self): response = self.client.get('/Customer/Create/', name='CustomerCreate') csrftoken = response.cookies['csrftoken'] self.client.post("/Customer/Create/",{ 'csrfmiddlewaretoken': csrftoken, 'customer_name': smart_str(u'veeers'), 'primary_contact': smart_str(u'veereseeree'),} ,headers={"X-CSRFToken": csrftoken},name='Creating') Here is the code i got from Internet.Its not working for me. Customer has name, primary_contact and some attributes .. i want to save the data from Locust Testing Tool to DB. to know the Performance of post method with some pages -
Is it safe to save logs in single file for all workers processing a queue?
I have multiple workers for a single queue. celery -A my_project worker -l info -P eventlet --concurrency=20 -Q my_queue-n worker1@%%h celery -A my_project worker -l info -P eventlet --concurrency=20 -Q my_queue-n worker2@%%h ........... ........... celery -A my_project worker -l info -P eventlet --concurrency=20 -Q my_queue-n worker30@%%h Is it safe to save logs into a single file say "my_queue.log"? from all its workers? Note: tasks in this queue are executed periodically every 0.5 seconds -
Serialize data from multiple models django
Is it possible to serialize data from multiple models in django? For example, my code below currently will provide JSON of the data from my "Build" model. serializers.py class buildStatsAPI_serializer(serializers.ModelSerializer): class Meta: fields = ('id','author_id','buildDescrip','buildStart','buildNotes') model = Build views.py class buildStatsAPI(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = buildStatsAPI_serializer def get_queryset(self): machinesOwned = CustomUser.objects.filter(customerTag=self.request.user.customerTag).filter(isDevice=True) machineList = [] for machine in machinesOwned: machineList = machineList + [machine.id] query = Build.objects.filter(deleted=0, author_id__in=machineList,).values().order_by('pk') return query How can I include data from other models on the same serializer? Specifically, I am currently serializing the 'author_id' which is a foreign key from my CustomUser model. I would like to get the 'authorName' from this model and include it on the same JSON object. -
cassandra django engine cqlsh error while its installed via pip
I am new to cassandra, I started to test it with Django but I have some problem with it, first I followed the tutorials and I passed this part : python manage.py sync_cassandra Creating keyspace dbnew [CONNECTION default] .. Syncing sth.models.User the first problem is I cannot find my database, I run a code in my shell to show me the path of database but my database is not there. the second problem I have is that in cmd when I want to run cassandra I get this error: ERROR 12:04:54 Exception encountered during startup org.apache.cassandra.io.FSWriteError: java.nio.file.AccessDeniedException: C:\Program Files\DataStax Community\data\commitlog\CommitLog-5-1550053481425.log at org.apache.cassandra.io.util.FileUtils.deleteWithConfirm(FileUtils.java:132) ~[apache-cassandra-2.2.3.jar:2.2.3] at org.apache.cassandra.io.util.FileUtils.deleteWithConfirm(FileUtils.java:149) ~[apache-cassandra-2.2.3.jar:2.2.3] at org.apache.cassandra.db.commitlog.CommitLogSegmentManager.recycleSegment(CommitLogSegmentManager.java:358) ~[apache-cassandra-2.2.3.jar:2.2.3] at org.apache.cassandra.db.commitlog.CommitLog.recover(CommitLog.java:173) ~[apache-cassandra-2.2.3.jar:2.2.3] at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:273) [apache-cassandra-2.2.3.jar:2.2.3] at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:513) [apache-cassandra-2.2.3.jar:2.2.3] at org.apache.cassandra.service.CassandraDaemon.main(CassandraDaemon.java:622) [apache-cassandra-2.2.3.jar:2.2.3] Caused by: java.nio.file.AccessDeniedException: C:\Program Files\DataStax Community\data\commitlog\CommitLog-5-1550053481425.log at sun.nio.fs.WindowsException.translateToIOException(Unknown Source) ~[na:1.7.0_72] at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) ~[na:1.7.0_72] at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) ~[na:1.7.0_72] at sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source) ~[na:1.7.0_72] at sun.nio.fs.AbstractFileSystemProvider.delete(Unknown Source) ~[na:1.7.0_72] at java.nio.file.Files.delete(Unknown Source) ~[na:1.7.0_72] at org.apache.cassandra.io.util.FileUtils.deleteWithConfirm(FileUtils.java:126) ~[apache-cassandra-2.2.3.jar:2.2.3] ... 6 common frames omitted and the last problem I have is when I run command python manage.py dbshell it returns cannot find cqlsh error while I installed it via pip -
how can I print out the Retail price and the Cost price of a product in django oscar?
In django oscar when creating a product in stock and pricing step there are options ( Cost Price , Price (excl tax) , Retail price ) the Price (excl tax) is the price is showing on the product view how can I show the retail or the cost price alongside the Price (excl tax) ? my desire is to make an old price and new one like 100$ down from 300$ I want to use the existing product form to fulfill this task I mean the 100$ be in the retail or cost price and then I print it in the product template alongside the Price(excl tax) how can I print it ? -
Auto print option in xhtml2pdf python library
def pdf_invoice(request, id=None): # some code return render_to_pdf( 'voucher_pdf/voucher_pdf.html', { 'pagesize': page_size, 'title': title, 'init_data': init_data, } ) def render_to_pdf(template_src, context_dict): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.CreatePDF(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) The pdf print options get populated when I call the pdf_invoice function through url. but I need auto print dialog option.. Is there any solution. If the question is unclear do let me know. -
Using Django SimpleHistory and TabularInline together
I want to display the ModelA as a TabularInline of ModelB and at the same time want to maintain the history of changes to ModelA using the Django simple history module. Is there a way to do this? Went through the official documentation of both TabularInline and Django simpleHistory but couldn't get much out of it. Model A class ModelAInline(admin.TabularInline): model = ModelA def has_add_permission(self, request, obj=None): return False Model B class ModelBAdmin(admin.ModelAdmin): list_display = ("name",) search_fields = ("name",) readonly_fields = ("last_changed",) inlines = (ModelAInline,) -
How to deny access or show appropriate message to unauthorized users access urls of django.contrib.auth?
I'm making an user authentication app using Django authentication framework. I'm using provided views like LoginView and other views (from django.contrib.auth). Problem is when users (authenticated or anonymous) access urls: path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), they see the these pages. for example the page that confirms that a link to reset their password has been sent to their email. while the user is already signed in and they didn't ask for password reset and there is no email send to their email because they never asked to reset their password. they just manually accessed email has been sent confirmation page 127.0.0.1:8000/account/password_reset/done/. How to prevent them from accessing these urls or show them appropriate message? -
How do I get list of cities of certain countries?
I am trying to show names of the cities of a certain countries {{city}}. For example if I click "USA" it should show the list of the cities in my database. But I don't know how to filter it right. I tried this but nothing show up. Post.objects.filter(country='country').filter(city='city') This is my model class Post(models.Model): title = models.CharField(max_length=255) country = models.CharField(max_length=255) city = models.CharField(max_length=255) address = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone = models.CharField(max_length=255) website = models.CharField(max_length=255) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('users:blog') This is my view def cities(request): context = { 'posts': Post.objects.filter(country='country').filter(city='city') } return render(request, 'users/cities.html', context) This is my template: {% for post in posts %} <table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;"> <tbody> <tr> <td>{{ post.id }}</td> <td>{{ post.city }}</td> </tr> </tbody> </table> {% endfor %} {% endblock %} </div> -
Enrich Django QuerySet different outcomes
Goal Querying for all products, slicing them, returning subset of those products with an added key:value , in other words, enriched. Code that works but I can't use I can't use this code because I use a paginator, the paginator accesses hte count of the QuerySet. If I pass the sliced QuerySet then that count is just for that sliced part, not the overall QuerySet, hence why I can't use it. products_qs = final_qs[paginator.get_offset(request): paginator.get_offset(request) + paginator.get_limit(request)] for product in products_qs: product.raw['super_cool_new_key'] = ms_response.get('results').get(product.id) This works great, when I print the data I can see that super_cool_new_key enrichment in every product. Awesome. Problem? Well, I have had to slice it and now the count method is no longer true. Of course, I can do something like: products_qs.count = final_qs.count and move on with my life, but it feels... hacky, or maybe not? Code I would like for it to work, but doesn't for i in range(paginator.get_offset(request), paginator.get_offset(request) + paginator.get_limit(request)): product = final_qs[i] product.raw['super_cool_new_key'] = ms_response.get('results').get(product.id) When I see the output of the data, the super_cool_new_key is not there. I can't wrap my head around as to why? Suspicions It's obvious it's something about the code difference that is the culprit … -
Django how to use url pk value inside the GCBV (generic classbase view)
i am designing generic class base view inside which i want to use the value of pk (primary key) from url pattern how can i do it? i have tried view base solution using two parameter (request, pk). But how can it done using gcbv post method. Django url pattern urls.py url(r'^(?P<pk>[0-9]+)/add_product/$', views.AddProduct.as_view(), name='add_product') views.py class AddProduct (LoginRequiredMixin, CreateView): login_url = '/login_user' redirect_field_name = 'redirect_to' model = Product template_name = 'shopsurfer/add_product.html' fields = ['name', 'category', 'lot', 'specs', 'price', 'product_logo'] def form_valid(self, form): object = form.save(commit=False) pk = ***here want pk from url*** object.shop = get_object_or_404(Shop, pk=pk) object.save() return super(AddProduct, self).form_valid(form) i want to sore the pk value inside the variable PK which is declared inside the AddProduct -
Django 2.1.7 get session key
I know this is a possible duplicate post, I found a solution for this, but those posts are from older versions of Django and I can't get the new syntaxis. Could someone give me a tip please? I'm trying to prevent users to use the same account simultaneously. So when someone log in an account, if the user and pass are ok, I'm iterating the django_session table in order to find if theres any other session with the same account, if yes, close this session and start the last one. After auth.authenticate(blah blah): if user is not None: # Checks if there's any other active session with the same account for session in Session.objects.filter(session_key=request.session.session_key): # //aq data = session.get_decoded() print(data.get('_auth_user_id', None)) if data.get('_auth_user_id', None) == str(user.id): session.delete() But something is not working with this syntaxis. I can't get the session user's ID. When a user logs in I'm using request.session['logueado'] = user.id and auth.login(request, user). This should be like a "last to log in wins" system. -
DRF ModelViewSet saving related_name field
Is it possible to update related_name field without tricky moves like that? I need "companies" field to fill selector choices and fill Zone with Companies relations. So it should contain name param and be like [{"pk": 42, "name": "company_name"}]. So then I'll get pk of selected choices and update the record. Serializer class ZoneSerializer(serializers.ModelSerializer): companies = serializers.SerializerMethodField(method_name='_get_companies') def _get_companies(self, obj): return Company.objects.filter(zone=obj).values('id', 'name') def save_object(self, obj, **kwargs): obj.companies = Company.objects.filter(pk__in=self.init_data.get("companies", [])) super(ZoneSerializer, self).save_object(obj, **kwargs) class Meta: model = CompanyZone fields = ("id", "companies")