Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python How to send an attachment with mailgun
Good day I need help please. I can't send a message with attachment. This is the relevant resource: def send_email_with_mailgun(sender, recipients, subject, body, mail_gun_url, mailgun_api_key): recipients = recipients if type(recipients) is list else [recipients] try: return requests.post( mail_gun_url, auth=("api", mailgun_api_key), data={"from": sender, "to": recipients, "subject": subject, "text": body}, files=[("attachment", (open("xxxxxxx.pdf", "rb")))],) except: pass If I remove the parameter it does send, otherwise it will not -
How to reference a ForeignKey using a population script with Django
I'm creating a job ticket system and it's all working how I want it to so far, but I can't get my population script to add in several jobs to test with. The first two models get populated as expected. It crashed on the third... I'm not sure how to add in Foreign Key references into this. populate_jobs.py: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'petiqjobrequest.settings') import django from django.core.files import File django.setup() from jobs.models import Brand, JobType, Job IMG_DIR = os.path.dirname(os.path.realpath(__file__)) IMG_DIR += '/jobs/static/images/' testIMG = IMG_DIR + "local_advecta.png" def populate(): brands = { "Advecta": {"shortname": "ADV", "logo": IMG_DIR + "logo_advecta.png"}, ... } jobtypes = [ { "name": "Assets", "description": "Logos, Product Photography, Stock Images" }, ... ] jobs = [ { "name": "A new job request", "brand": "Advecta", "job_type": "Assets", "due_date": "2018-03-01", "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum id dolor auctor, mollis nisi sed, vestibulum arcu. Proin sem neque, fermentum a metus et, bibendum varius ligula." }, ... ] for brand, brand_data in brands.items(): b = add_brand(brand, brand_data["shortname"], brand_data["logo"]) print('Brands made') for j in jobtypes: j = add_jobtype(j["name"], j["description"]) print('Jobs Types made') for job in jobs: job = add_job( job["name"], job["brand"], job["job_type"], job["due_date"], ) print("Jobs added") def add_brand(name, … -
Why can't Django 2.0.1 be found when running Circle CI?
I'm running Circle CI on a Django project. The build fails, and the results show that Django 2.0.1 couldn't be installed. Why is the build failing? I was previously using Gitlab CI without any problems. The installation runs from my requirements.txt which contains Django==2.0.1. config.yml # Python CircleCI 2.0 configuration file # # Check https://circleci.com/docs/2.0/language-python/ for more details # version: 2 jobs: build: docker: # specify the version you desire here # use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers` # - image: circleci/python:3.6.1 - image: python:latest # Specify service dependencies here if necessary # CircleCI maintains a library of pre-built images # documented at https://circleci.com/docs/2.0/circleci-images/ # - image: circleci/postgres:9.4 working_directory: ~/repo steps: - checkout # Download and cache dependencies - restore_cache: keys: - v1-dependencies-{{ checksum "requirements.txt" }} # fallback to using the latest cache if no exact match is found - v1-dependencies- - run: name: install dependencies command: | python3 -m venv venv . venv/bin/activate pip install -r requirements.txt - save_cache: paths: - ./venv key: v1-dependencies-{{ checksum "requirements.txt" }} # run tests! # this example uses Django's built-in test-runner # other common Python testing frameworks include pytest and nose # https://pytest.org # https://nose.readthedocs.io - run: name: run tests command: … -
Django auto populate author field in admin panel
In my django project i have a model.py with a class like this: class temp_main(models.Model): descr = models.CharField(max_length=200, verbose_name="Description") notes = models.TextField(null=True, blank=True, verbose_name="Note") dt = models.DateTimeField(auto_now=True) #Fields for API permissions owner = models.ForeignKey('auth.User', related_name='tmain_owner', on_delete=models.CASCADE, verbose_name="API Owner") class Meta: verbose_name = '1-Main Template' verbose_name_plural = '1-Main Templates' def __str__(self): return self.descr i would that in my admin panel the owner field was auto-populated with the current login user. In my admin.py i write: admin.site.register(temp_main, ) How can i set my owner field with logged in user? Thanks in advance -
Why am I unable to serialize my query via DRF?
class execution_details(APIView): def get(self): this_job_execution = JExecutionSerializer(this_job_execution) payload = [{ 'binaries': binaries, 'stage_logs': stage_logs, 'job_logs': job_logs, 'external_link': ext_links,}] return Response(this_job_execution.data + payload) error unsupported operand type(s) for +: 'ReturnDict' and 'list' I'm wondering if there is an issue because this_job_execution is a single record rather than a queryset with multiple records. I know I have done this in the past with a queryset, so that's why I suspect this is an issue. -
Django CMS:: Deserialization Error :: page has no field named 'path'
I have a Django application which is using Django CMS. I had built custom plugins, pages, users etc. in the application using CMS. I want to export the CMS data from my application to another instance of the same application which doesn't have any cms related data. I am using the following command: python manage.py dumpdata cms djangocms_column djangocms_file djangocms_googlemap djangocms_link djangocms_picture djangocms_style djangocms_text_ckeditor djangocms_video > cms_export.json --indent=2 I copied that file to the other app instance and tried to load it using the following command: python manage.py loaddata cms_export.json I got the following error: django.core.serializers.base.DeserializationError: Problem installing fixture '/cms_export.json': Page has no field named 'path' cms_export.json snippet: [{ "model": "cms.usersettings", "pk": 1, "fields": { "user": 2, "language": "en", "clipboard": 1 } }, { "model": "cms.usersettings", "pk": 2, "fields": { "user": 1, "language": "en", "clipboard": 7 } }, { "model": "cms.page", "pk": 4, "fields": { "path": "0004", "depth": 1, "numchild": 0, "created_by": "script", "changed_by": "xxxx", "parent": null, "creation_date": "2018-01-27T18:51:08.122Z", "changed_date": "2018-02-04T19:48:21.804Z", "publication_date": "2018-01-27T18:52:43.340Z", "publication_end_date": null, "in_navigation": true, "soft_root": false, "reverse_id": null, "navigation_extenders": null, "template": "base.html", "site": 1, "login_required": false, "limit_visibility_in_menu": null, "is_home": true, "application_urls": "", "application_namespace": null, "publisher_is_draft": true, "publisher_public": 5, "languages": "en", "revision_id": 0, "xframe_options": 0, "placeholders": [ 3, … -
Making a Django form appear on click
I have a Django form that is inside a div that I'm trying to get to appear when the user clicks on that div, but to no avail. Funnily enough though if I force the state of the element in the browser console it will work. Here's my code: {% if user.is_authenticated %} <div style="text-align:left;" class="content-editor"> <p class='body-font'>{{ post_detail.text|linebreaksbr }}</p> <!-- the form should only appear on click for the authenticated user --> <form method="POST" class="edit-prompt">{% csrf_token %} {{ form.text }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% endif %} CSS: .edit-prompt { visibility:hidden; } .edit-prompt:active { visibility: visible; } .content-editor { background-color: transparent; opacity: 1; border: none; width:inherit; height:inherit; } .content-editor:hover { border: 1px solid #ccc; border-radius: 5%; width: inherit; height: inherit; cursor: pointer; } -
Init django server with start-stop-daemon like a service
I'm trying to init a virtualenv and runserver command of django project on Ubuntu 16 Linux I create a file on /etc/init.d/initfile with the commands to start and stop service: do_start() { echo -n "Starting " $NAME " ..." if [ -f $PIDFILE ] then echo "\n-> Service " $NAME " is running." else start-stop-daemon --start --background --quiet --name $NAME --pidfile $PIDFILE --make-pidfile --exec $DAEMON echo "\n-> Service " $NAME " started..." fi } and the $DAEMON is a file with: VIRTUALENV_DIR=/home/user/python/DjangoProjects/newEnv1 SITE_DIR=/home/user/python/DjangoProjects/newEnv1/sampleSite source $VIRTUALENV_DIR/bin/activate python $SITE_DIR/manage.py runserver 0:8080 but when I check the process with ps -fu root is generated 3 pid id: 22875, 22878 and 22880 Image with multiple pid ids the problem is, when I execute the stop command only stopped the pid id that include in $PIDFILE but the other is running yet so the server still running. Can you help me please ? thanks -
Retrieve a script variable in all apps - Django
I've been searching and trying several solutions for a what it seems a simple problem for data retrieval of an externally executed script in Django. Now, I've figured out how to execute a script once through the Django's "AppConfig" (Execute code when Django starts ONCE only?), but I also need to retrieve at least once the data this script gathers across all Django's applications. Since it is a "sensorial" data, It shouldn't be included in a database or stored in any other way. What is the best way to do this? What am I missing? Thanks in advance for any heads up. -
Combining DataTables with Django Ajax Requests
I have a Django project that has a model Analytic that lists analytics. I followed this guide: https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html to implement Ajax calls, and it worked perfectly. Then, I implemented DataTables to hold the data instead of a regular Bootstrap table. On the surface this worked well, but now the Ajax calls don't work. Instead, saving the create/update forms and deleting a row requires a page refresh for changes to take effect. Here is my JS: $(function () { /* Functions */ var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-analytic").modal("show"); }, success: function (data) { $("#modal-analytic .modal-content").html(data.html_form); } }); }; var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#analytic-table tbody").html(data.html_analytic_list); $("#modal-analytic").modal("hide"); } else { $("#modal-analytic .modal-content").html(data.html_form); } } }); return false; }; /* Binding */ // Create analytic $(".js-create-analytic").click(loadForm); $("#modal-analytic").on("submit", ".js-analytic-create-form", saveForm); // Update analytic $("#analytic-table").on("click", ".js-update-analytic", loadForm); $("#modal-analytic").on("submit", ".js-analytic-update-form", saveForm); // Delete analytic $("#analytic-table").on("click", ".js-delete-analytic", loadForm); $("#modal-analytic").on("submit", ".js-analytic-delete-form", saveForm); var table = $('#analytic-table').DataTable( { fixedHeader: true, language: { search: "", searchPlaceholder: "Table Search", lengthMenu: "Show _MENU_", }, dom: … -
How do we do signup email confirmation on Google App Engine?
What is the best way to implement signup email confirmation using django-allauth on Google App Engine flexible environment? This seems to be a glaring hole in Google App Engine documentation. Although, there are several links talking about email, none of the documentation gives a complete example that works for us. We've tried sending smtp.gmail.com with our GAE account administrator gmail address without success. This is our Django config: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'our_admin_account@gmail.com' EMAIL_PASSWORD = "'********" EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'our_admin_account@gmail.com' Even though we have 'our_admin_account@gmail.com' as authorized email sender and disabled captcha. However, this didn't do the trick for us. Also, we have purchased G-Suite because we thought that it would be easier to setup on GAE. We tried using a G-Suite email address to send without any success. This has been quite infuriating and a total waste of our time. We are thinking about moving over to Amazon cloud instead -- but would rather not take the time loss in switching if it could be avoided. We don't want to waste another couple of days trying the other third party email options on GAE--like SendGrid, MailChimp--without knowing whether or not … -
UnicodeDecodeError in Django Raw Query using bytes as parameter
For Django (python3) I am writing a unit test to ensure that a custom encryption routine can be decrypted by MySQL's native aes_decrypt function. start_value = 'A Simple starting test value.' enc_value = mysql_aes_encrypt(start_value, cipher=self.cipher) self.cursor.execute('SELECT aes_decrypt(%s, %s) FROM DUAL', (enc_value, self.test_key)) When executed, this raises the following exception: # -- snip -- File "/home/vagrant/virtualenv/members/lib/python3.6/site-packages/MySQLdb/cursors.py", line 187, in _do_get_result self.description = self._result and self._result.describe() or None UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 13: invalid start byte When examining the source to execute it seems that after the query executes it attempts to describe the results and dies. I thought maybe I could pass in a column alias to the query as it was having trouble with the bytes there but that didn't work. SELECT aes_decrypt(%s, %s) as foo FROM DUAL In the end, I wrote a stub class that extends cursor and set the cursorclass of the default connection to be that stub. class NoDescriptionCursor(Cursor): """ Testing Cursor """ def _do_get_result(self): """ Our version doesn't try to get descriptions """ db = self._get_db() self._result = self._get_result() self.rowcount = db.affected_rows() self.rownumber = 0 self.description = None # Overridden to run the query. self.description_flags = None # Overridden to … -
How to change Django datetime field format in datepicker?
I have a model field called close_date models.py class Project(models.Model): close_date = models.DateTimeField(blank=True, null=True) In my forms, I don't do add any classes to display this because I will do it in my template using django-widget-tweaks. However, my forms look like this: forms.py class NewProjectForm (ModelForm): class Meta: model = Project fields = ['close_date', ...] templates {% load widget_tweaks %} <div class="form-group" id="close_date"> <label>{{project_form.close_date.label}}</label> <div class="input-group date"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span> {% render_field project_form.close_date class="form-control" type="text" %} </div> </div> <script> $('#close_date .input-group.date').datepicker({ todayBtn: "linked", keyboardNavigation: false, forceParse: false, calendarWeeks: true, autoclose: true }); </script> All this works fine, I can display the form, save it to the database and even display data to the user, but when I want to edit the this object and I populate the form from my views, I see this in the datepicker input field: 2018-02-28 00:00:00 How can I change what is displayed there from 2018-02-28 00:00:00 to 02/28/2018? Is that on the django side of things or the JS side? -
How to connect a Docker container to PostgreSQL running on the localhost using a DATABASE_URL?
I'm following the Aptible Django Quickstart Tutorial which described how to create and deploy an app Aptible's PaaS. I would also like to be able to run the Docker container with the Django app locally and connect to a local PostgreSQL database, however, and it is unclear to me how to do this. The Dockerfile for the Django app is: FROM python:3.6 # System prerequisites RUN apt-get update \ && apt-get -y install build-essential libpq-dev \ && rm -rf /var/lib/apt/lists/* # If you require additional OS dependencies, install them here: # RUN apt-get update \ # && apt-get -y install imagemagick nodejs \ # && rm -rf /var/lib/apt/lists/* # Install Gunicorn. If Gunicorn is already present in your requirements.txt, # you don't need that (but if won't hurt). RUN pip install gunicorn ADD requirements.txt /app/ WORKDIR /app RUN pip install -r requirements.txt ADD . /app EXPOSE 8000 CMD ["gunicorn", "--access-logfile=-", "--error-logfile=-", "--bind=0.0.0.0:8000", "--workers=3", "mysite.wsgi"] where mysite is the name of the Django app. Its settings.py uses dj-database-url as follows: import dj_database_url DATABASES = {'default': dj_database_url.config()} In order to connect to a local instance of PostgreSQL, it would seem I should follow the Docker for Mac Solution on Allow docker container … -
Celery task to write file in subprocess
There is a celery task to call subprocess and in the subprocess script, I want to write some text in file (auth_path) each function in script done. The problem is, if I call python3 apt.py from shell, text written in the file. but when i call subprocess in task, progress works correctly, all functions works in apt.py but nothing written in aut_path. Why I cannot write some texts when I call script from subprocess. @task(name="dene") def dene(): cmd = ['timeout', '240', 'python3', "apt.py"] output = check_output(cmd) in apt.py there is a write func and calling it again and again. def write_out_auto(msg): with open(aut_path, 'a') as the_file: the_file.write(msg +'\n') write_out_auto("Finished the section 2") -
how to parse an image into api directly
This is how my program works: I'm parsing an image taken by my camera into an emotion detection API and then getting the result via the following html: {% extends "app/layout.html" %} {% block content %} <form action="{% url 'upload' %}" method="post" enctype="multipart/form-data" id="form1"> {% csrf_token %} <div > {% load staticfiles %} <input id="id_file" name="file" type="file" src="{% static 'app/content/image0000000.jpg' %}" width="100" height="30"/> <!--this DO NOT WORK --> </div> <button type="submit" >Submit</button> </form> {% endblock %} The relevant python files are as follow: from django.shortcuts import render from django.http import HttpRequest from django.template import RequestContext from datetime import datetime from .forms import UploadFileForm from projectoxford.Client import Client from projectoxford.Emotion import Emotion from tempfile import TemporaryFile from django.conf import settings from PIL import ImageDraw from PIL import Image import base64 def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) form = UploadFileForm() return render( request, 'app/index.html', context_instance = RequestContext(request,{'form':form}) ) def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] modified, happyscore = handle_uploaded_file(file) modified.seek(0) image = base64.b64encode(modified.read()) return render(request, 'app/result.html', {'image': image, 'ishappy':happyscore}) else: form = UploadFileForm() return render(request, 'app/index.html',{'form':form}) def handle_uploaded_file(file): client = Client.emotion(settings.OXFORD_KEY) recognizeResult = client.recognize({'stream': file}) im = Image.open(file) draw = ImageDraw.Draw(im) … -
Can't find virtualenv in path even though its there
I'm trying to set up Django. I have Python 3.6 installed, and I installed virtualenvwrapper using pip3. Here is what my bash profile looks like: # Get the aliases and functions if [ -f ~/.bashrc ]; then . ~/.bashrc fi export PATH="$PATH:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/3.6/bin/virtualenv" export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 export PROJECT_HOME=$HOME/Devel source /Library/Frameworks/Python.framework/Versions/3.6/bin/virtualenvwrapper.sh Every time I run $ mkvirtualenv my_django_env I get ERROR: virtualenvwrapper could not find virtualenv in your path -
Not able to pass value from view to onclick in template
i'm not able append the callurl sending to template from view to onclick <button class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--primary" onclick="location.href ='{% url 'home:{{callurl}}'%}'"> <i class="material-icons">add</i> </button> when i am passing the like above i'm getting error like Exception Value: Reverse for '{{callurl}}' not found. '{{callurl}}' is not a valid view function or pattern name. -
Django: trying to link to one model inside of other models ListView
I would like to get the Restaurant Id from the Restaurant model and use it for the href in the Lunchmenu listview. Don´t really know how to move forward from here. I have tried a for loop of the "restaurants_list" in the template but did not really understand how to get only one Id from the list. Is there any way to do this in the template? Should I change the View somehow? Models: class LunchMenu(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) class Restaurant(models.Model): manager = models.ForeignKey(User, on_delete=models.CASCADE) restaurant_name = models.CharField(max_length=100) Listview: class LunchMenuListView(ListView): template_name = "lunchmenus/lunchmenu_home.html" model = LunchMenu def get_context_data(self, **kwargs): context = super(LunchMenuListView, self).get_context_data(**kwargs) context["restaurants_list"] = Restaurant.objects.all() return context Template: <div class="row"> {% for lunchmenu in lunchmenu_list %} <div class="col-lg-4 col-sm-6 portfolio-item"> <div class="card h-100"> <a href="/restaurants/{{restaurant.id}}"><img class="card-img-top" src="http://placehold.it/350x200" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="#">{{lunchmenu.restaurant}}</a> </h4> <p class="card-text">{{lunchmenu.description | safe}}</p> </div> </div> </div> {% endfor %} </div> {% endblock %} -
Bug Update Django Formsets
I am trying to modify a sale in which I have this view: #Views.py class VentaUpdate(UpdateView): model = Venta template_name = 'venta/venta_form.html' form_class = VentaForm success_url = reverse_lazy('venta:ventas_listar') def get_context_data(self, **kwargs): data = super(VentaUpdate, self).get_context_data(**kwargs) if self.request.POST: data['detalleformset'] = DetalleFormSet(self.request.POST, instance=self.object) else: data['detalleformset'] = DetalleFormSet(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() detalleformset = context['detalleformset'] with transaction.atomic(): self.object = form.save() if detalleformset.is_valid(): detalleformset.instance = self.object detalleformset.save() return super(VentaUpdate, self).form_valid(form) It works correctly in these cases: 1. Edit a product (if it was 1 soda, replace it with 1 water). 2. Add another product. But it does not work to want to eliminate a product from the sale. #forms.py class DetalleForm(forms.ModelForm): class Meta: model = DetalleVenta fields = [ 'producto', 'cantidad', 'subtotal', ] labels = { 'producto':'Producto', 'cantidad':'Cantidad', 'subtotal':'Subtotal', } widgets = { 'producto':forms.Select(attrs={'class':'form-control'}), 'cantidad':forms.NumberInput(attrs={'class':'form-control'}), 'subtotal':forms.NumberInput(attrs={'class':'form-control'}), } DetalleFormSet = inlineformset_factory(Venta, DetalleVenta, form=DetalleForm, extra=1) And so that the formset is dynamic, that is to be able to add more fields which I think the error is from the Javascript but I can not find the error {% extends 'base/base.html' %} {% load static %} {% block titulo%} Registrar venta {%endblock%} {% block contenido %} <form method="post"> {% csrf_token %} <div class="col-md-4 … -
del_user() missing 1 required positional argument: 'username' - Django
I'am looking a solution for my problem. I have a something like a my own admin panel, and I want to create a users managment system. The first I want to create a definition to delete the registered users. But when I try to execute this def, the system responde me a error : del_user() missing 1 required positional argument: 'username' My views.py is : from django.shortcuts import render from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from .forms import LoginForm, UserRegistrationForm from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib import messages ... def del_user(request, username): try: user = User.objects.get(username=username) user.delete(user) message.succes(request, 'Pomyślnie usunięto') except User.DoesNotExist: message.error(request, 'Użytkownik nie istnieje') return render(request, 'konto/settings.html') And I created a url to del_user.html page **urls.py** from django.urls import path from django.contrib.auth import views as auth_views from .views import dashboard, register,settings, del_user ... path('del_user/', del_user, name='del_user'), ... I don't understand this error why is not working. Anybody help? -
Django session dictionary KeyError when attempting to replace
I am dealing with a third-party authorization issue on the backend and encountering strange session store behavior. When I detect that the third part session authorization has become invalid, I re-authenticate and I am attempting to update the data in the session, which is not working. The problem is that after I delete the key from the session, I get a KeyError when I try to replace it once I have the updated information. def my_session_thing(invalidate=False): if invalidate: del self.request.session['my_session_dict'] self.request.session.modified = True my_session_dict = self.request.session.get('my_session_dict') if my_session_dict is not None: self.current_session_dict = my_session_dict return my_new_session_dict = { 'foo': 'bar' } # ** Why does this raise a KeyError when invalidate is True? ** self.request.session['my_session_dict'] = my_new_session_dict I am currently exploring alternatives to this strategy, but I found this behavior contradicts the dictionary-like behavior that the "How to use sessions" documentation describes, so it would be worth posting. -
Django Test: Model not updating
I am writing a test in django using django.test.TestCase. In setupTestData(cls), I create a User instance. test_user1 = User(username='testuser',email="a@b.com") test_user1.set_password('12345') test_user1._category = 'Male' test_user1.save() I have also set up a class in myapp.models where I have a post_save signal to add an object to a model MyModel. @receiver(post_save,sender=User) def update_mymodel(sender,instance,created,**kwargs): MyModel.objects.create(user=instance,category=category) The thing is, the receiver is called and the MyModel object should be created. But when I do MyModel.objects.all() in my test file, it shows empty. Why is the user instance not in the model? -
Django carts Error
Hi i have a problem in (add to cart button and remove from cart ) the default for me when i click add to cart the item should stores in carts object and redirect me to the cart_(home)page but it doesnot work it stay me in the existing page and dont add or remove product Here is my: carts/models.py class cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL , null=True, blank=True) products = models.ManyToManyField(product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects=CartManager() def __str__(self): return str(self.id) def __unicode__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': products = instance.products.all() total = 0 for x in products: total += x.price if instance.subtotal != total: instance.subtotal = total instance.save() m2m_changed.connect(m2m_changed_cart_receiver, sender=cart.products.through) def pre_save_cart_receiver(sender, instance, *args, **kwargs): if instance.total>0: instance.total = instance.subtotal else: instance.total=0.00 pre_save.connect(pre_save_cart_receiver, sender=cart) and my carts/views.py def cart_home(request): cart_obj,new_obj=cart.objects.new_or_get(request) return render(request,"carts/home.html",{"cart":cart_obj}) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect('cart:home') cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) # cart_obj.products.add(product_id) return redirect('cart:home') -
Can't load static files in Django from views.py
I am trying to load static files(image files) in the web page by creating a list in views.py and put it in a list which has html elements and then passing to the jinja to render below home.html {% extends "Home/layout.html" %}. {% load staticfiles %} {% block content %} {% include 'Home/includes/header.html' %} <div class="container"> <div class="row"> {% for x in data %} {{ x|safe }} {% endfor %} </div> </div> {% endblock %} views.py from django.shortcuts import render from django.http import HttpResponse from .models import DB from utils.processDB import ProcessDB import os def index(request): ls = os.listdir() lsf = [] for x in ls: if os.path.isfile(x): lsf.append(x) data = ProcessDB(DB,lsf).dbProcess() #this will return a list of html which will have <img> tags like below #<img src="{% static "Home/img/image.png"%}"/> context = {'data': data} return render(request,'Home/home.html',context) when i inspect the rendered web page i see the image tag like this<img src="{% static "Home/img/image.png" %}" /> not what it should be <img src="Home/img/image.png"/> so y it is not loading static files when i m try the above instead loading this <img> tag If I pass the image list directly to jinja and change the views.py to pass a list of tuple(html,img) …