Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do static files won't load in the web app?
So I've seen a lot of tutorials here explaining what to do, but no matter what I change the static files won't seem to load. This is what my files are looking like atm settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(PROJECT_ROOT, "static"),''] job_app/urls.py urlpatterns = [ path('', main, name='index'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) index.html <!DOCTYPE html> <html lang="en"> <head> <title>JobPortal - Free Bootstrap 4 Template by Colorlib</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% load static %} <link href="https://fonts.googleapis.com/css?family=Nunito+Sans:200,300,400,600,700,800,900" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/animate.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.theme.default.min.css' %}"> <link rel="stylesheet" href="{% static 'css/magnific-popup.css' %}"> <link rel="stylesheet" href="{% static 'css/aos.css' %}"> <link rel="stylesheet" href="{% static 'css/ionicons.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-datepicker.css' %}"> <link rel="stylesheet" href="{% static 'css/jquery.timepicker.css' %}"> <link rel="stylesheet" href="{% static 'css/flaticon.css' %}"> <link rel="stylesheet" href="{% static 'css/icomoon.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> jobber/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('job_app.urls')) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
How django template url matching works
I'm trying to figure out how url matching works in django template. What i'm trying to achieve is when clicking on a link it would bring up a specific objects. Models.py class PostManager(models.Manager): def get_queryset(self): return super(PostManager,self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = (('published','Published'), ('draft','Draft ')) FIELD_CHOICES = (('1','1 Title and body field'), ('2','2 Title and body fields'), ('3','3 Title and body fields'), ('4', '4 Title and body fields'), ('5', '5 Title and body fields')) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post') title = models.CharField(max_length=100) sub_title = models.TextField(max_length=50,default="") title_1 = models.CharField(max_length=100,null=True,blank=True) title_1_body = models.TextField(null=True,blank=True) title_2 = models.CharField(max_length=100,null=True,blank=True) title_2_body = models.TextField(null=True,blank=True) title_3 = models.CharField(max_length=100,null=True,blank=True) title_3_body = models.TextField(null=True,blank=True) title_4 = models.CharField(max_length=100,null=True,blank=True) title_4_body = models.TextField(null=True,blank=True) title_5 = models.CharField(max_length=100,null=True,blank=True) title_5_body = models.TextField(null=True,blank=True) created = models.DateField() publish = models.DateTimeField(default=timezone.now) slug = models.SlugField(max_length=250, unique_for_date='created') status = models.CharField(max_length=250, choices=STATUS_CHOICES, default='draft') object = models.Manager() postManager = PostManager() class Meta(): ordering = ('publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[self.slug]) def get_image_filename(instance, filename): title = Post.title slug = slugify(title) return "media/%s-%s" % (slug, filename) class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='images') image_1 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) image_2 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) image_3 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) image_4 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) image_5 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True) views.py def post_detail(request): post = get_object_or_404(Post) return render(request, 'blog_application/templates/single.html', {'post':post}) index.html {% for elem in … -
Is It Possible To Have A Theme Selector For Users To Choose The Style of Their Site?
I was wondering if it's possible to have a option for users to pick from a set of themes/styles they want for there site like wordpress or forums? I plan on releasing a script for people to use but I don't want them to all have the same theme so I would like to have a option for them to select one they like that I created or have them be able to upload/create there own from the admin cp Thanks anyone for the help! -
UNIQUE constraint failed on adding a new model field in django
When i want to add a new field called slug to my Post model in Djnago, the migrate command will raise UNIQUE constraint failed: new__chat_post.slug After that i remove that field from my model but the problem still exists. why?? and how to resolve this problem without deleting my whole table data?? The database is sqlite3 and the Django version is 2.2 . thanks. The model: class Post(models.Model): title = models.TextField(max_length=100) context = models.TextField(max_length=255) creation_date = models.DateTimeField(default = timezone.now) author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete = models.CASCADE) slug = models.SlugField(default=["title"],unique=True) -
Django Template Passing form input to url
I am trying to add form input data in url. this is my current template where I pass the parameter smith hardcoded: <input type="text" placeholder="Search.." name="name"> <a href="{% url 'data' name='smith' %}">Search</a> I don't pass the parameter dynamically, I mean, input data will be parameter like name=inputdata How can I do it? Can anyone help me? -
How to properly use FieldKeys to verify data in separate models?
I'm making a form that has a few fields in my model. The first field of this model, called EmployeeWorkAreaLog is Employee#/adp number. I have another model, called Salesman that is used as the main database with all the employees, and has each person's info, along with their employee #. What I was trying to achieve is that the form doesn't submit if the employee # is not valid, meaning is not currently in Salesman model. Below is what I tried to do, but I noticed that this is tying the Employee # to the auto-generated ID in the database, not the adp_number. I tried to make some changes with how the relation is but every time I ended up having to modify the Salesman model, which I cannot do, because it said something about the field being unique. Note that, in my EmployeeWorkAreaLog, the same employee can have multiple entries, so I don't know if that's what might be causing this. How could I approach this without changing Salesman? And, secondary question, not as crucial, is there any way that, upon submission, I can copy the slsmn_name from Salesman into the corresponding employee_name? I had created the get_employee_name() function, … -
upgrading Django and Python versions, problem with default value for FloatField set to string
In a model using Django 1.8 and Python 2.7 we had a migration that accidentally set the default value for a FloatField to an empty string (default=''), which Django appears to have interpreted as a bytes-string: class Migration(migrations.Migration): dependencies = [ ('reo', '0030_merge'), ] operations = [ migrations.CreateModel( name='ProfileModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('pre_setup_scenario_seconds', models.FloatField(default=b'', null=True)), ], ), ] After upgading to Django 2.2 and Python 3.6, Django gives the warning with manage.py migrate that there are un-migrated changes. After changing the default value from '' to None and running manage.py makemigrations we get: operations = [ migrations.AlterField( model_name='profilemodel', name='pre_setup_scenario_seconds', field=models.FloatField(default=None, null=True), ), ] Then running manage.py migrate yields: nlaws-> python manage.py migrate Operations to perform: Apply all migrations: auth, contenttypes, django_celery_results, proforma, reo, resilience_stats, sessions, summary, tastypie Running migrations: Applying reo.0050_auto_20191030_1738...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/Users/nlaws/.virtualenv/api/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate … -
"The value of 'list_display[1]' refers to 'discount', which is not a callable, an attribute of 'OfferAdmin'
when i run server i am facing error : : (admin.E108) The value of 'list_display[1]' refers to 'discount', which is not a callable, an attribute of 'OfferAdmin', or an attribute or method on 'products.Offer'. I tried following piece of code in a file named admin.py from django.contrib import admin from .models import Product, Offer class OfferAdmin(admin.ModelAdmin): list_display = ('code', 'discount') class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') admin.site.register(Offer, OfferAdmin) admin.site.register(Product, ProductAdmin) before adding class OfferAdmin code was working fine. However after adding it. this is showing error I'm using django version 2.1.5 -
Django request timeout for some static files when running manage.py test package.to.unit.test
Context: We run Cypress tests which use instances of our application started using manage.py test package.test.suite. The test fixtures and environment are all set up using a class extended from django.contrib.staticfiles.testing.StaticLiveServerTestCase. A unit test/method is added to the extended class which invokes Cypress as a subprocess to run the tests and asserts against the exit code of the subprocess. Versions: Python: 3.6.8 Django: 2.2.3 macOS: Mojave 10.14.6 The problem: This worked well until yesterday when I updated Cypress via npm. Now when I start a server using manage.py test some.test.suite the server will fail to serve all of the static resources requested by the browser. Specifically, it almost always fails to serve some .woff fonts and a random javascript file or two. The rest of the files are served but those 5 or 6 which the browser never receives a response for. Eventually I'll get a ConnectionResetError: [Errno 54] Connection reset by peer error (stack trace below) in the terminal. Additionally, if I enable the cache in my browser and attempt a few refreshes things will work fine, almost as if theres a limit to the number of files that can be served at once and once some files are … -
Django-Channels with 2 applications
I'm trying to make an example to test if it is possible to have 2 independent django apps connected to the same channel from django-channels. So far, I was able to make an example running on one machine and 2 other machines being able to access the first via a client. But the goal is to be able to connect separate applications in a single channel to communicate. Is that possible? If not, do you know an alternative? Note: I'm also using redis, if that helps. Thank you! -
Selenium keeps a cache?
I have a more complicate question but I'm trying to isolate the problem to avoid confusion. I'm testing a page using selenium. In this page there are two javascript external scripts. If you go there manually the page is working correctly but using selenium one of the javascript isn't loaded: The script from “http://localhost:55234/static/js/common.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type. 2 add-name Loading failed for the <script> with source “http://localhost:55234/static/js/common.js”. Checking the source (right click => view page source) gives me correctly the template with this two lines (and the others, off course): [...] <!-- load global javascript --> <script type='text/javascript' src="/static/js/common.js"></script> <!-- load app javascript --> <script type='text/javascript' src="/static/lists/js/lists.js"></script> [...] the src are clickable. Cliking the first one reload the source page without the line three and four, so without this lines: <!-- load app javascript --> <script type='text/javascript' src="/static/lists/js/lists.js"></script> Cliking the second one (lists.js) gives the javascript code. But! But this code looks an (very) old version of my code. Many days old (isn't too long to be cached?). At that time all the code was in one javascript file (lists.js) and the other one (common.js) didn't existed so … -
AttributeError in Serializer Django
I am developing an app, and one of its features is that it can recognize the device, but sometimes it doesn't get anything back. It maybe an error from the API that i'm using. The model Device is the following: class Device(models.Model): """ """ user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) deviceModel = models.CharField(max_length=128, verbose_name=_(u"Device Model")) deviceId = models.CharField(max_length=128, verbose_name=_(u"Device ID")) packageId = models.CharField(max_length=128, verbose_name=_(u"Package ID")) tokenId = models.TextField(verbose_name=_(u"Token ID")) platformId = models.CharField(max_length=10, verbose_name=_(u"Plataforma ID")) created_at = models.DateTimeField(auto_now=True, verbose_name=_(u"Created")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_(u"Updated")) def __str__(self): return u'Device: {0}'.format(self.deviceId) def __unicode__(self): return self.__str__() def send_logout(self): """ Send logout Notification Message """ active_session = ActiveSession.objects.filter( device=self ).first() if active_session: push_service = FCMNotification(api_key=settings.FCM_API_KEY) data_message = { "action": "Logout", "token_id": active_session.token_jwt } push_service.single_device_data_message( registration_id=self.tokenId, data_message=data_message, content_available=True ) And the serializer is: class DeviceSerializer(ModelSerializer): def create(self, validated_data): # Check if exist device = Device.objects.filter(user=validated_data["user"], deviceId=validated_data['deviceId']).first() today = timezone.now() # If exist, update if device: device.tokenId = validated_data['tokenId'] device.updated_at = today device.save() logger.info("[Device] Updated deviceID {} with token {} for user {}".format( validated_data['deviceId'], validated_data['tokenId'], validated_data["user"].username )) else: device = Device(**validated_data) device.save() logger.info("[Device] Created deviceID {} with token {} for user {}".format( validated_data['deviceId'], validated_data['tokenId'], validated_data["user"].username )) # Associate Device to ActiveSession active_session = ActiveSession.get_active_session(self.context.get('request')) active_session.device = device active_session.save() return device … -
How to link your page to another page without using <a> tag
i have three Html page home.html, destination.html and login.html. Home.html only button my task is very simple if i click on this button if user is authenticated than go to the destination page otherwise go to the login page(i use builtin login function and that's working properly) my view.py is ``` from django.contrib import auth from django.shortcuts import redirect, render from rest_framework.permissions import IsAuthenticated """ this view section for home.html and destination.html, i have use builtin function for login """ def home(request): if request.method == 'POST': user = auth.authenticate() if user is IsAuthenticated: return render(request, 'destination.html') else: return redirect('login/') else: return render(request, 'home.html') def destination(request): return render(request, 'destination.html') ``` my urls.puy ``` from django.contrib import admin from django.urls import path from newapp import views from django.contrib.auth.views import LoginView urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('destination', views.destination, name= 'destination'), path('login/', LoginView.as_view(template_name='login.html')), ] ``` -
'CharField' object has no attribute split
i am creating an website where a user can search for recipes by their ingredients. I wish that when a user finally see recipe, ingredients there would be splited with ', ' in view. for now it is just space. I tried to do this in my model, but they i get error as in title - 'CharField' object has no attribute split. Models: from django.db import models class Ingredient(models.Model): ingredient_name = models.CharField(max_length=250) igredient_name1 = ingredient_name.split(', ') def __str__(self): return self.ingredient_name1 class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return self.recipe_name template: <div> <h1><a href="/">Drink drank drunk</a></h1> </div> {% for drink in results %} <div> <p>{{ drink.recipe_name }}</p> <p>Preparation: {{ drink.preparation }}</p> <p>Ingredients: {% for ingredient in drink.ingredients.all %} {{ingredient.ingredient_name}} {% endfor %} </p> </div> {% endfor %} view: def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') q = Q() for queries in query.split(', '): q |= (Q(ingredients__ingredient_name__icontains=queries)) results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) -
How from a Python variable to refer to <!-- Images. -- >?
There is a Python {{ object variable.background }}, which outputs the selected background from the database . When the background of the color ('#c6aa99', '#E1A600', it correctly displays the scene aframe. But when the variable is set to the image value 'mars',' star ' does not display the background of the image on the scene. How to make the value of a variable, when assigned to 'star', 'wars' refer to to upload pictures to the scene? <a-scene id="aframe" foo > <a-assets> <!-- Images. --> <img id="star" src="https://ucarecdn.com/30d7b1e6-2867-4396-a64d-8fb41e69ce0d/"> <img id="city" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/city.jpg"> <img id="cosmos" src="https://ucarecdn.com/34a5bbdb-1820-44c3-a848-26acd9356bbe/"> <img id="sechelt" src="https://ucarecdn.com/40714251-095c-407e-9b5f-76f361db3b78/"> <img id="blank" src="https://ucarecdn.com/fc2d2aa9-08b0-4d05-931c-85b78130d758/"> <img id="mars" src="https://ucarecdn.com/4496c535-1b3d-4c1c-a24f-8fa6bcfb895a/"> <img id="dey" src="https://ucarecdn.com/1bbbf75b-cc02-450a-91af-e528a6eaf8a1/"> <img id="blue" src="https://c1.staticflickr.com/3/2929/33929340355_1fb4ecf6e0_k.jpg"> <img id="wasteland" src="https://c1.staticflickr.com/5/4556/24549684008_5b18834af3_o.png"> </a-assets> <!-- General Enviornment --> <!-- Background selected when creating a new scene (taken from the database ) --> <a-sky id="sky" color="{{ object.background }}"></a-sky> <a-light type="ambient" intensity=".5" color="#FF54CA"></a-light> {% endblock %} <!-- Text written by the user when creating a new scene (taken from the database) --> <a-plane id="ground" position="0 0 0" rotation="-90 0 0" width="100" height="100" color="#00FF00" material="roughness: 1;"></a-plane> </a-entity> </a-scene> -
Using only gunicorn, django, and whitenoise how do I serve media?
I have my website finally working properly, but media files aren't served when debug = False what should I do? I've went through hell trying to make it work with nginx following this tutorial but it kept breaking and not serving static among other things, so I went with pure gunicorn and whitenoise. I really am not an expert at deploying, only development. Please help. Security isn't a problem with media files because only the admin can upload them, not end-users. Specifically I need to know if it's the end of the world leaving debug = True just for media files. Or if there's an easy way to serve them with debug = False. -
Error in SQL query with connection.cursor()
I am making a query with connection.cursor(), but I get the following error column does not exist LINE 1: SELECT u.id, u.addByAdmin FROM core_user AS u WHERE u.role... ^ HINT: You probably want to refer to the column «u.addByAdmin». This is my code @action(detail=False, methods=['get']) def registertalentsdetail(self, request,pk=None): cursor = connection.cursor() query = "SELECT u.id, u.addByAdmin FROM core_user AS u WHERE u.role = 'TA';" cursor.execute(query) conter = cursor.fetchall() print(conter) return Response(data=conter) Any idea how to fix this? -
How can to run task in 5 minutes after finish previous task using celery-beat?
I have a two tasks - a and b. Task a running in 5 minutes after finish previous task a. Task b running in 3 minutes after finish previous task b. How can I implement it? I'm use python 3.6.8, Django 2.2.6 and celery 4.3.0? -
Django - How to make a ForeignKey dropdown into a textbox?
I have a form that has a field which is a ForeignKey since it makes sure that the ID # being entered is one that exists in the database. After making it be a ForeignKey, it changed my field to look like a dropdown in the form as shown below, that contains a bunch of options called "Salesman object ('a number')", instead of it being a text box like it was before. The user is supposed to be able to enter their "adp" number and it should only allow numbers in salesman. Before I had made this change, I just had the adp_number under fields in forms.py, and not as a ForeignKey, which made me not be able to cross check with the Salesman model which contains all the valid adp_number's. I tried following this Django: using ForeignKeyRawIdWidget outside of admin forms since I'm not using admin either, but once I made the field into a widget it just stopped showing on my page altogether and I'm not sure what needs to be changed. forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'adp_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('adp_number').remote_field, site), } fields = ('work_area', 'station_number') models.py class EmployeeWorkAreaLog(models.Model): employee_name = models.CharField(max_length=25) adp_number … -
how to add Paginator to search result using django?
hello i want add Paginator in search result page how to do this ? my code : views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') # page = request.GET.get('page', 1) # the_home_page is the name of pages when user go to page 2 etc if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidapk_database= AndroidApks.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidgames_database= AndroidGames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) antiruvs_database= Antivirus.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) systems_database= OpratingSystems.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcgames_database= PCgames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database)) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') html page : {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h1> <small> Results for {{ request.GET.q }} : </small></h1> <br/><br/> {% for result in results %} <label id="label_main_app"> <img style="margin-top:.3%;margin-left:.3%" id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="160" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} <br> <br> <a href="{{ result.page_url }}" type="button" class="btn btn-primary"><big> See More & Download </big> </a> </p> </label> {% endfor %} {% else … -
How should images used in jquery-ui be loaded in django admin?
I added an action to django admin which requieres a modal and some javascript interaction. I used jquery-ui for the modal and was able to load it following this instructions: django admin jQueryUI dialog However, the modal has a broken image (the closing button). The question is how can I reference that image so jquery-ui can find it. I put the images from jquery-ui library on the same folder where I put the .js and .css files I'm using for the action. The close image of the modal is broken, trying to find it on http://localhost:8000/static/admin/js/jquery-ui-1.12.1.custom/images/ui-icons_777777_256x240.png The project path is static/admin/js/jquery-ui-1.12.1.custom/images/ui-icons_777777_256x240.png The current code I have for referencing the assets is: admin.py class ReservationBaseAdmin: list_display = (..., 'action') # some more code (...) # Here I reference the jquery-ui library and the js code I wrote for the action class Media: css = { "all": ("admin/css/tables.css", 'admin/js/jquery-ui-1.12.1.custom/jquery-ui.min.css', 'static/admin/js/jquery-ui-1.12.1.custom/jquery-ui.structure.min.css') } js = ( 'admin/js/jquery-ui-1.12.1.custom/jquery-ui.min.js', 'admin/js/jquery-ui-1.12.1.custom/jquery-ui.structure.min.css', 'admin/js/front_iframe.js", "admin/js/force_sync.js' ) # some more code (...) def action(self, obj): front = env('FRONT_URL') url = reverse('admin:traveller_traveller_change', args=[obj.traveller.pk]) edit_button = format_html('<a class="button front_link" data-front="{}" target="_blank" href="{}">Ver Perfil</a>', front, url) refresh_button = format_html('<a class="button force_sync" data-confirmation-number="{}" >Forzar sincronización</a>', obj.reservation.confirmation_number) return edit_button + refresh_button action.short_description = "Acciones" static/admin/js/force_sync.js … -
Embedding seaborn generated plot image in Django Template
I am trying to embed the image generated by the seaborn plot dynamically into the Django HTML template. While when I am trying to save, the correct image gets saved in my directory. But my requirement is to pass this image in HTML page/Template without saving in the directory. I used BytesIO to stream the bytes and encoded the bytes with base64.b64encode encoding. But I get a blank white image on the page instead. fig = sb.pairplot(kpi) tmpfile = BytesIO() fig.savefig(tmpfile, format='png') encoded = base64.b64encode(tmpfile.getvalue()) return encoded Html file: <img src='data:image/png;base64,{{description}}'> {{description}} -
Django datadump and loaddata not working due to fixture error
Here is how I tried to dump mysql DB: python3 manage.py dumpdata > dumpdata.json Then, I tried to reload it: python3 manage.py loaddata dumpdata.json This is the error that I get: json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 226398200 (char 226398199) django.core.serializers.base.DeserializationError: Problem installing fixture '/home/JCDR77/HospitalThree/dumpdata.json': -
The current path, account/active/Z1s6IYaohOJWeRV4, didn't match any of these
enter image description here urls.py: path('active/(?P<active_code>.*)/$', ActiveUserView.as_view(), name='active_user'), views.py: class ActiveUserView(View): def get(self,request,active_code): users = UserProfile.objects.filter(code=active_code) if users: users.is_active = True users.save() else: users.delete() return HttpResponse('Fail!Register Again!') return HttpResponseRedirect(reverse("account:user_login")) -
Saving multiple text inputs from form into one field in django class-based view
I'm trying to save about 9 inputs from different textbox fields in template to one field on the django database, linking them each to another field. What can be done? What I'm trying to achieve is to get log input for each department and save in field log and linked to the department of the logged in user real_index.html (Template File) <script> function ch() { $(".div1").hide() $(".div2").show(); var a = document.getElementById("userInput").value; displayUserInput.innerHTML= a; } function cha() { $(".div2").hide() $(".div3").show(); var b = document.getElementById("userInpu").value; displayUserInpu.innerHTML= b; } ... <form action="" method="post" > {% csrf_token %} {{ form | crispy }} <table class="table table-bordered"> <thead class="table-primary"> <th>Time</th> {% for log in object_list %} {% if user.username == log.username%} <th>{{ log.dept }}</th> {% endif %} {% endfor %} </thead> <tbody> <tr class="table-success"> <td> 6:30AM-7:30PM </td> <td> <div id="div1" > <div class="div1" id="div1"> <input type="text" id="userInput" name="userInput"/><input class="btn2" class="btn2" type="button" value="Done" onclick="ch()"/> </div> </div> <span id="displayUserInput"></span> </td> models.py class Log(models.Model): ... dept = models.ForeignKey(Dept, null=True, on_delete=models.SET_NULL) log = models.CharField (max_length=50,null=True) forms.py ... class NewLogForm(forms.ModelForm): #class NewLogForm(forms.MultiValueField,forms.MultiWidget): class Meta(): model = Log fields = ('log','dept',) views.py class NewLogView(generic.CreateView): model = Log form_class = NewLogForm template_name = 'dutylog/real_index.html' def get_success_url(self, ): return reverse_lazy('index',) def form_valid(self, form): …