Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Message appearing twice
I've came across an issue where message is displayed twice even though its called only once. Sometimes only one message is displayed however, most of the time 2 messages are. My view: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Account created has been creted! You can log-in now.') return redirect('login') else: if request.user.is_authenticated: messages.error(request, 'You are loged-in and in order to registrate you must be loged-out.') return redirect('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form,'title':'Register Page'}) And here is my template Base.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title> Django blog - {{ title }}</title> {% else %} <title> Django blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> {% if … -
Query Django models two levels down foreign key relations
I am building a dictionary application using Django. The main models in this app are Expressions, Definitions, and Citys. The logic is that each Expression has one or more Definitions, and each Definition is associated with one City. Here is my problem: I want to query all the Citys associated with an Expression, from the Expression level. For example, I would like to do an_expression.cities and get all the Citys associated with (each Definition of) an_expression. Here are my models: class City(models.Model): city = models.CharField() class Expression(models.Model): expression = models.CharField() cities = models.ManyToManyField(City, related_name="expressions") class Definition(models.Model): city = models.ForeignKey(City, related_name="definitions") expression = models.ForeignKey(Expression, related_name="definitions") This code now works. However, every time I add a Definition I need to add the City to both the Expression --AND-- the Definition itself. Here is my question: Is there a way to only add the City to the Definition, and then somehow be able to query an_expression.cities and get all cities (basically getting rid of the cities field in the Expression model)? -
Handling data as well as response in AJAX success
I am handling submit through ajax using django in backend: Here is ajax code: $.ajax({ data: $(this).serialize(), // get the form data type: $(this).attr('method'), // GET or POST url: $(this).attr('action'), success: function(response,data) { if(data.frame_width_absent){ Alert.render('Please enter frame-width'); } else if(data.frame_height_absent){ Alert.render('Please enter frame-height'); } else if(data.frame_fps_absent){ Alert.render('Please Enter frame-fps'); } else if(data.bit_rate_absent){ Alert.render('Please Enter Bit-Rate'); } else if(data.bit_depth_absent){ Alert.render('Please Enter bit-depth'); } else if(data.container_absent){ Alert.render('Please Enter container'); } else if(data.duration_absent){ Alert.render('Please Enter container'); } else if(data.HRD_support){ Alert.render('HDR10 and HDR10+ content generation is not supported'); } else{ $('#frame').html(response); } } }); //Alert.render('Success If generation fails you will receive an email'); return false; }); The problem is if response is my first parameter in success the response is displayed optimally while alert is not displayed(when all required parameters are not entered). If the data is my first part parameter in success Alert is displayed optimally(when certain parameters in form are not entered) but unable to display response part(when all parameters in form required are entered). Back-End code views.py def generate(request): global frame_width,frame_height,frame_fps,video_codec,bit_rate,container,scan_type,profile,bit_depth,count if video_codec!='HEVC' and video_codec!='VP9': bit_depth='8' print("inside_tasks") #print(type(bit_depth)) if not frame_width: data = { 'frame_width_absent': True } return JsonResponse(data) elif not frame_height: data = { 'frame_height_absent': True } return JsonResponse(data) #return … -
Showing a rtsp stream on React Frontend
I need to show a video stream on a react component with a Python+Django backend. CURRENT SITUATION: I'm using opencv library to get the stream: import cv2 [...] def read_data(): cap = cv2.VideoCapture("rtsp://user:password/bla bla bla") while(cap.isOpened()): ret, frame = cap.read() retval, buffer = cv2.imencode('.jpg', frame) image_result_base64 = base64.b64encode(buffer) return HttpResponse(image_result_base64, 200) On React, where this.state.response_data is the content responseText of the backend call: render () { const img_data ="data:image/png;base64," + this.state.response_data; return <img id="overView" class="overView" alt="Stream" src={ img_data} width="90%" /> } This approach works and on frontend I see the frame in my component. Unfortunally to create some sort of stream, I need to call backend at least 10 times every second to have 10fps. This is heavy to backend. I read about StreamingHttpResponse but I don't know if fits my needs. -
Markdownx does not render math formulas
i'm new here. For one month ago i have started to learn Django. My goal was to make a web app: a pool of mathematical questions. User can create new questions and filter questions with respect to topic and level of difficulty. Yesterday, i decided to include a preview for textarea like the preview for example in stackoverflow. After searching in google i have found markdownx. It renders the text and all html-tags but not mathematical formulas (see picture).example of the issue I use mathjax to render mathematical formulas. If i put for example x^2 between \( ... \) it disappears. Same problem with $$...$$. Does anybody know how fix this problem? Below you can find my settings.py, models.py and the template. settings.py INSTALLED_APPS = [ 'question.apps.QuestionConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectfield', 'latexify', 'django_filters', 'mathpool', 'rest_framework', 'markdownx', 'markdown', ] MARKDOWNX_MARKDOWNIFY_FUNCTION = 'markdownx.utils.markdownify' MARKDOWNX_MARKDOWN_EXTENSIONS = [ 'markdown.extensions.extra', 'mdx_math', 'markdown.extensions.sane_lists', 'markdown.extensions.nl2br', ] models.py from django.db import models from multiselectfield import MultiSelectField from django.contrib.auth import get_user_model from django.urls import reverse from markdownx.models import MarkdownxField YEARS = ( (3, '3'), (4, '4'), (5,'5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10'), ) POINTS = [ ('1', '1'), ('2', '2'), ('3','3'), … -
Making password required for admins, but unusable for users
I am trying to implement a Django backend for a mobile app where users authenticate through their mobile numbers only. When the user tries to login, the backend will send him an OTP so that he can login. For this use case, I think I don't need a password field. However, I think I need a password for superusers. I am thinking of a solution but I don't know whether it is a suitable solution. models.py: class UserManager(BaseUserManager): def create_user(self, email, phone_number, password=None): user = self.model(email=email, phone_number=phone_number) user.set_password(password) user.save() return user def create_superuser(self, email, phone_number, password=None): user = self.create_user(email, phone_number, password) user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(blank=False, null=False, unique=True) phone_number = PhoneNumberField(blank=False, null=False, unique=True) is_staff = models.BooleanField(default=False, blank=False, null=False) objects = UserManager() USERNAME_FIELD = 'phone_number' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email'] def __str__(self): return self.phone_number Will the code above do the job? -
'str' object has no attribute 'get' Django Middleware [closed]
I am currently new to django framework and I am making a Middleware for authentic redirection of pages within a website. So if the user is guest user I want to always make him redirect to login page. But I came with this error. I have tried HttpResponse and return redirect but it didn't worked for me. I am getting this Attribute error at all the pages I am accessing to This shows me along with the error "'str' object has no attribute 'get'" My MiddleWare Code is: import re from django.shortcuts import redirect from django.conf import settings from django.contrib.auth import logout from django.urls import reverse from django.http import HttpResponse EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') path = request.path_info.lstrip('/') print(path) #if not request.user.is_authenticated: # if not any(url.match(path) for url in EXEMPT_URLS): # return redirect(settings.LOGIN_URL) url_is_exempt = any(url.match(path) for url in EXEMPT_URLS) if path == reverse('logout').lstrip('/'): logout(request) return redirect('/accounts/') if request.user.is_authenticated and url_is_exempt: return redirect(settings.LOGIN_REDIRECT_URL) elif request.user.is_authenticated or url_is_exempt: return None else: return(settings.LOGIN_URL) This is my link of the … -
Make Custom Filter to iterate each field and check condition to return
I am making Custom Filter. It should check the each JSONField of model and pick up rows depending on conditions. These are the code what I want. How can I solve this?? class MyText(models.Model): myJson = JSONField() class MyTextFilter(filters.FilterSet): post_date = filters.DateTimeFilter(method="post_date_filter") def post_date_filter(self, queryset, name, value): for mt in MyText: jsonObj = json.loads(mt.myJson) if jsonObj['postdate'] > value: #do something here???? #return something here????? class Meta: model = MyText -
how can i get request.PUT or PATCH method body or data In Django Request
i am working on django request response log middleware i can't get request.PUT or PATCH but when i have a post request or get request i can have the data also i have request.body but it is empty as well in form of byte string. this is my code class RequestResponseLogger(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) request_body= request.PUT, response_body=response_body, method=request.method.lower(), status_code=response.status_code, return response any help is appropriated! -
URL available in urls.py still getting 404 in Django 2
I wrote a function in views.py as follows def removeinvoices(request,invoiceID,creatorID,deletorid,typeofchange): form = invoicestorageForm() form.invoiceid = invoiceID form.creatorid = creatorID form.deletorid = deletorid form.typeofchange = typeofchange form.save() thatInvoice = taxInvoice.objects.filter(invoiceid=invoiceID).first() thatInvoice.delete() messages.success(request, "Invoice ID "+ invoiceID +" removed Successfully !") return redirect("vieweinvoices") and wrote in urls.py as follows: path("removeinvoices/<int:invoiceID>/<int:creatorID/><int:deletorid>/<str:typeofchange>", views.removeinvoices, name="removeinvoices",), and I'm generation the href in JS dynamically, I'm able to get all variables coorectly, but is still says 404 error, when I click on href I'm able to work fine with all other urls mentioned in image. Not sure where I'm going wrong! -
How to extract csv file from a zip and save it to disk in python?
I have a zip file that I receive from the user. The zip file contains a csv file which I need to save to a directory in my server. I am using django in my backend and this is what I do from zipfile import ZipFile from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def store_file(request): if request.method == "POST": user_id = request.POST.get("user_id") client_file = request.FILES['attachment'] file_path = "/home/sr/uploads/" try: with ZipFile(client_file, 'r') as zip_ref: csv_file = zip_ref.infolist()[0] with open(file_path + '%s' % csv_file, 'wb+') as dest: for chunk in csv_file.chunks(): dest.write(chunk) # return success message return HttpResponse(0) except Exception as e: # return error message return HttpResponse(1) But I get this error message Traceback (most recent call last): File "/home/sr/scripts/interact.py", line 2364, in store_file for chunk in csv_file.chunks(): AttributeError: 'ZipInfo' object has no attribute 'chunks' Now this is how I usually store a csv file when it comes to me as just a csv file. But now in this case, the csv file is inside a zip and so even after pulling the csv file from the zip, I can't save it in my server. What am I doing wrong? -
<textarea not working with django and python
I am trying to make this textarea work, but it doesnt. my view doesnt receive the data from this. My Input works: <input id="contact_email" type="text" name="contact_email" value="" class="form-control" placeholder="Seu E-mail *" required="" data-validation-required-message="Please enter your email address."> What is wrong on that <textarea id="contact_message" type="text" name="contact_message" value="" class="form-control" placeholder="Seu E-mail *" required="" data-validation-required-message="Please enter your email address."></textarea> my view code bellow: def myfunc(request): contact_name = request.GET.get('contact_name') contact_email = request.GET.get('contact_email') contact_mensagem = request.GET.get('contact_mensagem') print('hello world') print(contact_name) print(contact_email) print(contact_mensagem) return HttpResponse("Email Enviado!") -
Django session and cycle_key()
I'm using Django as backend server and it has configure SESSION_ENGINE with django.contrib.sessions.backends.cache, cache is stored in Redis. Despite it appears to be configured correctly, the coockie session_id never change, so if I login and I set session_id to the request, response will give me the same session_id (with the new data). This behaviour exposes me to Session fixtation attack and I do not know why cycley_key() is never called. Someone knows hot to fix this behaviour? Thanks! -
Rapidsms installation
I want to install rapidsms; I use the ubuntu version 19.10. I applied this tutorial https://rapidsms.readthedocs.io/en/develop/tutorial/tutorial01.html And when i used this command : python manage.py syncdb I have this error : (rapidsms-tut-venv) abdou96@abdou96-Vostro-3460:~/rapidsms_tut$ python manage.py syncdb /home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django_tables2/tables.py:175: RemovedInDjango19Warning: SortedDict is deprecated and will be removed in Django 1.9. attrs["base_columns"] = SortedDict(parent_columns) /home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django_tables2/tables.py:197: RemovedInDjango19Warning: SortedDict is deprecated and will be removed in Django 1.9. attrs["base_columns"].update(SortedDict(cols)) /home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/rapidsms/utils/modules.py:7: RemovedInDjango19Warning: django.utils.importlib will be removed in Django 1.9. from django.utils.importlib import import_module Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django/core/management/init.py", line 354, in execute_from_command_line utility.execute() File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django/core/management/init.py", line 328, in execute django.setup() File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django/init.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/selectable/apps.py", line 10, in ready from . import registry File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/selectable/registry.py", line 6, in from selectable.base import LookupBase File "/home/abdou96/rapidsms-tut-venv/local/lib/python2.7/site-packages/selectable/base.py", line 12, in from django.urls import reverse ImportError: No module named urls -
How to customize Django's CSRF handling on a per view basis
In a Django application I have 'django.middleware.csrf.CsrfViewMiddleware' enabled. This means that a POST request without a CSRF token will be rejected and result in a HTTP response Forbidden (status code 403). Now I have one view that needs to handle a missing CSRF token in a different way. Instead of a 403 response I want to redirect the user to a different page. I came up with the following solution (based on the docs: https://docs.djangoproject.com/en/3.0/ref/csrf/#scenarios): @csrf_exempt # Disable CSRF middleware @requires_csrf_token # Apply customized CSRF middleware def my_view(request): if getattr(request, 'csrf_processing_done', False): # CSRF success, process request ... else: # CSRF failed, redirect return HttpResponseRedirect(...) Which is nice and short and seems to work perfectly fine. My issue however is that it relies on an implementation detail. The current version of Django only ever sets csrf_processing_done to True in the _accept method of CsrfViewMiddleware (https://github.com/django/django/blob/3.0.4/django/middleware/csrf.py#L141) The requires_csrf_token is based on a customized version of CsrfViewMiddleware that overrides _reject to do nothing (https://github.com/django/django/blob/3.0.4/django/views/decorators/csrf.py#L17) (it keeps _accept the same). So my current implementation will work as long as Django doesn't change the implementation of this middleware and decorator. Since csrf_processing_done is not part of the public API (I asked: https://code.djangoproject.com/ticket/31360), I'm left … -
Form not save with custom form fields
Good morning guys, I have a problem with a form. My code: models class AnagraficaGenerale(models.Model): ragionesociale = models.CharField(max_length=40, null=True, blank=True) forms class AnagraficaGeneraleForm(forms.ModelForm): class Meta: model = AnagraficaGenerale views @login_required def anagrafica_new(request): if request.method == "POST": form = AnagraficaGeneraleForm(request.POST or None) if form.is_valid(): form.save() return redirect('anagrafica_list') else: form = AnagraficaGeneraleForm() return render(request, 'Anagrafiche/anagrafica_new.html', {'form': form}) html {% extends 'FBIsystem/basenobar.html' %} {%load staticfiles %} {% block content %} <div id="page-wrapper"> <div class="panel"> <div class="panel-body"> <h3 class="title-hero"> Nuova Anagrafica </h3> <form method="POST" class="form-horizontal bordered-row"> {% csrf_token %} <div class="example-box-wrapper"> <div class="form-group"> <label class="col-sm-2 control-label" > Ragione Sociale:</label> <div class="col-sm-6"> {{ form.ragionesociale }} </div> </div> </div> <button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button> </form> </div> </div> </div> {% endblock %} Everything seems ok but not save, if I try with {{form.as_table}} it save. I think there is a problem with custom field but I don't know how. whats wrong? TY -
How to make django serve static files in development?
For some reason my django project doesn't see my static files, giving me 404 error, like so: "GET /static/js/main.js HTTP/1.1" 404 1757 I do everything in accordance with the official guide. Here is my project structrure: PMpro: -PMpro (main project) -users (app) -tasks (another app) -static --js --css --etc... -templates --template files... -manage.py My settings.py file: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('home/', TemplateView.as_view(template_name='index.html')) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In my .html file I's collecting static files and linking to corresponding css/js file like so: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/organicfoodicons.css' %}" /> I'm pretty sure I do everything in accordance with the official django guide, and yet my project doesn't see/serve my static files. I have already went through a number of similar problems people were posting here, and I have everything im my code exactly as it was advised, but the problem is still there. Folks, any suggestions? -
Django: Offer has many Products
How to make relation in Django that Offer model has has Products and Products beyond to the one Offer. from django.db import models class Offer(models.Model): city = models.CharField( max_length=100) street = models.CharField( max_length=100) offer_taken = models.BooleanField( default=False) products = # models.OneToManyField(Product) ?? class Product(models.Model): product_name = models.CharField( max_length=100) -
ValueError: not enough values to unpack (expected 2, got 0) in Django
My function doesn't take any arguments but I get this error not enough values to unpack (expected 2, got 0). I can print the values on the terminal but can't be displayed on the browser. I am fetching data from two database tables(Postgres) and put it in a select input in Django template. This is the method suppose to return the data to be displayed def get_categories(): myvars = {} sdet = {} items = CategoriesDB.objects.all() vals = '<option value="">Please Select Category</option>' try: for item in items: section_id = item.section_id gname = repr(item.section.section_name) sdet[section_id] = gname category_id = item.id category_name = item.category_name gcat = {'id': category_id, 'name': category_name} if section_id not in myvars: myvars[section_id] = [gcat] else: myvars[section_id].append(gcat) for var in myvars: otitle = sdet[var] otl = len(otitle) tshort = '%s ...' % (otitle[:100]) if otl > 100 else otitle vals += '<optgroup label="%s" title="%s">' % (tshort, otitle) gitems = myvars[var] for i, itm in enumerate(gitems): gname = str(itm['name']) itm_id = itm['id'] itl = len(gname) itms = '%s ...' % (gname[:100]) if itl > 100 else gname vals += '<option value="%s" title="%s">%s</option>' % ( itm_id, gname, itms) vals += '</optgroup>' except Exception as e: raise e else: # on returning … -
Django ContenTypes not saving "content_object" on Migration
Starting with an existing ModelA. Requirements: depending on ModelA.type, ModelA.example will be a relationship to ModelB or ModelC. pre existing ModelA instances need to be initialized with the default, depending on ModelA.type (ModelA.type is already not nullable) Current Solution: I created a generic relation on ModelA: class ModelA: ... example_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) example_id = models.PositiveIntegerField(null=True) example = GenericForeignKey("example_content_type", "example_id") I ran ./manage.py makemigrations wich created a migration with nullable fields I changed the example_content_type and example_id fields to not null ran makemigrations again and created the following custom RunPython before the auto generated changes: def set_default_example(apps, schema_editor): ModelA = apps.get_model("myExample", "ModelA") all_model_a = ModelA.objects.all() for model_a in all_model_a: example = None if model_a.type == "type_a": example = ExampleForTypeA.objects.create(foo="foo") if model_a.type == "type_b": example = ExampleForTypeB.objects.create(bar="bar") model_a.example = example model_a.save() trying to migrate this is throws with django.db.utils.IntegrityError: column "example_content_type_id" contains null values I manually created and assigned the content_type (only works if I assign the _id field). this still throws with: django.db.utils.IntegrityError: column "example_id" contains null values so I mannully created and assigned the example_id resulting the the following code: def set_default_example(apps, schema_editor): ModelA = apps.get_model("myExample", "ModelA") all_model_a = ModelA.objects.all() for model_a in all_model_a: example = None content_type … -
How to do Facial Recognition in android's chrome browser
I have done facial recognition in my website with OpenCV, Python language, Django framework and it is working in my laptop. Now when i run the website on localhost in android's chrome browser, instead of opening android phone's camera it opens the camera in the laptop. Any solution? -
how to create a new item in an html table after submission of a form?
Basically I am designing a web app (using django) that acts as an email sending service for broadcasting emails to specific users. Within the app I have my outbox which i got from a responsive bootstrap admin template, with mail items. What I would like to happen is for when a message is sent and the form is submit a new mail item would appear in my table containing the some of the contents of the mail that was sent just like gmail (e.g subject) this is the html used : <div class="table-responsive"> <table class="table mail-list"> <tr> <td> <div class="photo1"> <!--<img style="opacity: 0.5;" src="{% static '../static/assets/images/background.jpg' %}" alt=""></div>--> <!-- a single mail--> <div class="mail-item"> <table class="mail-container"> <tr> <td class="mail-left"> <!-- image was here ;-; --> </div> </td> <td class="mail-center"> <div class="mail-item-header"> <h4 class="mail-item-title"><a href="mail-view.html" class="title-color">{% cache None sidebar request.user.username %} {{Subject}} {% endcache %}</a></h4> </div> <p class="mail-item-excerpt">{% cache None sidebar %} {{Body}} {% endcache %}</p> </td> <td class="mail-right"> <p class="mail-item-date">2 hours ago</p> <p class="mail-item-star starred"> <a href="#"><i class="zmdi zmdi-star"></i></a> </p> </td> </tr> </table> </div><!-- END mail-item --> Not sure if this is all the info that would be needed but I am quite new to html and django and so … -
How to render the content of a variable in a different template with Django?
I have a button that generates a report in two variables: one has a short version of the information and the other contains a detailed version on it. The view renders the information of the short one with a template, let's call it template one. I need to place a button in template one that allows to see the content of the second variable in a different template and also in a new browser tab. Since the information is not stored in the database (so I cant' address it with ids) how can I pass the variable that contains the detailed report information (hundreds of rows)? Is it okay to try to pass it using the template tag 'url'...? (It feels like a wrong approach) -
Docker-compose does not work in docker-machine
I have a cookiecutter-django application with docker that works fine if I run it locally with docker compose -f local.yml up. Now I am trying to deploy it so first I created a docker-machine in my computer (using macOS Catalina) and activated it. Now, inside the docker-machine, the docker-compose build works fine, but when I run it, the application crashes. Any idea what can be happening? I have been trying to solve this for almost a week now... This are my logs when I do docker-compose up in the docker-machine: Creating network "innovacion_innsai_default" with the default driver Creating innovacion_innsai_postgres_1 ... done Creating innovacion_innsai_django_1 ... done Creating innovacion_innsai_node_1 ... done Attaching to innovacion_innsai_postgres_1, innovacion_innsai_django_1, innovacion_innsai_node_1 postgres_1 | 2020-03-16 08:41:12.472 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2020-03-16 08:41:12.472 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_1 | 2020-03-16 08:41:12.473 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres_1 | 2020-03-16 08:41:12.494 UTC [21] LOG: database system was shut down at 2020-03-16 08:31:09 UTC postgres_1 | 2020-03-16 08:41:12.511 UTC [1] LOG: database system is ready to accept connections django_1 | PostgreSQL is available django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", … -
MultiValueDictKey Error when submitting a form
I am new in Django, I am working on a website where user can edit his profile (first name, last name, username, email) and also change his profile picture with a separate form. The profile picture form save file when submitted, but the updateform display 'MultiValueDicKeyError at /account/edit' 'profile_pic' when the form is submitted. Here is my views. def profile_edit_view(request): form = ProfilePic(request.Post or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): pp = form.save(commit=False) pp.user = request.user pp, created = Profile.objects.get_or_create(user=request.user) pp.profile_pic = request.FILES['profile_pic'] pp.save() return redirect... else: form = ProfilePic() updateform = UpdateUserForm(request.POST or None, instance=request.user) if request.method == 'POST': if updateform.is_valid(): updateform.save() return redirect.... else: updateform = UpdateUserForm() context = {'form':form, 'updateform':updateform} return render(request, 'profile_edit.html' context)