Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Emoji in Django admin form turns into question marks
In my Django app, I have a setup roughly like so: there is a Model class with a template field @python_2_unicode_compatible class Message(models.Model): template = models.TextField(default=u'', help_text='Template string for message') Then inside my view code I have something like def view(request, message_id): message = get_object_or_404(Message, message_id__iexact=message_id) context = {...} return HttpResponse(Template(message.template).render(RequestContext(request, context))) Then I create Message objects and modify their template field through the Django admin site. I want to add emojis or other Unicode characters to one of my messages. I try copy-pasting an emoji into the text field, and save it, but on a refresh it's saved as a string of question marks instead of as the emojis. I've double-checked that I haven't touched DEFAULT_CHARSET (should be UTF-8), and I have <meta charset="utf-8"> in the source of both the admin site and the public site. Is there something I'm missing? -
How to use both (self , request) parameters in a function
class searchbox: def search(self , request): self.name=[] query1 = request.GET['search'] queryset = F360.objects.all() for items in queryset: if query1 == items.id: finid =items.f0_id if finuid is not None: try: url = "*******" querystring = {********} response = requests.request("GET", url, params=querystring) jData = response.json() name.append(jData["name"]) except: return redirect('loggedin') else: continue context = {'query1':query1, "name":self.name} return render(request , 'search.html', context) def details(self , request): name = self.name return render(request , "details.html", "name":name}) i am trying to create a django webapp i have defined a class with a method called search to make api calls and search from databases which works perfectly fine the problem is i wanna use the defined variables in another function called details but self and request both have to be the first parameter. how do i work around this. any help appreciated. Thankss -
Mac PyCharm terminal Python location changes when I move the Django project to another folder
I used PyCharm to create a Django project, then I moved the project to another folder for some reason. I can run and start the project, but when I click the terminal and type which python in PyCharm, I found the Python path is local Python path. How can I change the Python path to the project virtualenv path? I have changed the project interpreter to project virtualenv path in Preference I have changed the Preference - Tools - Terminal - Start directory to the project path, and the activate virtualenv is selected I have activated the virtualenv by source /Users/JackLi/Desktop/myproject/venv/bin/activate in pycharm terminal, but when I reopen the project, the Python path is still the local Python path -
How to deal with order migrate file?
I have model: class Student(models.Model): name = models.CharField(max_length=255) extend = models.IntegerField(blank=True, null=True) At migration file with name: 005_check I have a line: queryset = Student.objects.filter(name="Peter") But during migrate operation, my screening show "missing column extend" I figure out that extend column in Student table will have been added at migration file with name : 007_add_extend. migrations.AddField( model_name='student', name='extend', field=models.IntegerField(blank=True, null=True), ), How to queryset at migration file if column does not exist? -
python file write is not creating a new file
I have a django app, I received binary audio data from a javascript client, and I'm trying to send it to the google cloud speech to text API. The problem is that, python is not writing the binary audio data to a file. So I'm getting with io.open(file_name, "rb") as f: FileNotFoundError: [Errno 2] No such file or directory: '.........\\gcp_cloud\\blog\\audio_file.wav' I replaced the first part of the path with ........... Here is the client side code rec.ondataavailable = e => { audioChunks.push(e.data); if (rec.state == "inactive"){ let blob = new Blob(audioChunks,{type:'audio/wav; codecs=MS_PCM'}); recordedAudio.src = URL.createObjectURL(blob); recordedAudio.controls=true; recordedAudio.autoplay=true; sendData(blob) } } and here is my sendData function function sendData(data) { let csrftoken = getCookie('csrftoken'); let response=fetch("/voice_request", { method: "post", body: data, headers: { "X-CSRFToken": csrftoken }, }) console.log('got a response from the server') console.log(response) } and here is the DJango view that handles the binary audio data from the client def voice_request(request): #print(request.body) fw = open('audio_file.wav', 'wb') fw.write(request.body) file_name = os.path.join(current_folder, 'audio_file.wav') #file_name = os.path.join(current_folder, 'Recording.m4a') client = speech.SpeechClient() # The language of the supplied audio language_code = "en-US" # Sample rate in Hertz of the audio data sent sample_rate_hertz = 16000 encoding = enums.RecognitionConfig.AudioEncoding.LINEAR16 config = { "language_code": language_code, #"sample_rate_hertz": … -
How to build a user suggestion voting page in django?
How do you build something like this using Django - a suggestion page that users could provide feedback and upvote for things that they want to see next on the website such as new features, content, etc. Example: https://codecourse.com/roadmap If anyone could create, find, or provide snippets of code or even a github project that does something similar to this it would be very helpful for others who wish to do something like this. -
Django: Generate averages for ratings for a review site with multiple rating critera
Working on a project in Python(3.8) and Django, trying to implement a review system that has multiple criteria. Note: I've searched for awhile but haven't read anything that specifically solves my issue. I have 3 models: from django.db import models from django.conf import settings from django.urls import reverse # Create your models here. class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) def __str__(self): return self.name def get_reviews_count(self): return Review.objects.filter(company__board=self) .count() def get_last_review(self): return Review.objects.filter(company__board=self) .order_by('created_at') .first() class Company(models.Model): name = models.CharField(max_length=255, unique=True) #bio = models.TextField(max_length=4000) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, on_delete = models.CASCADE, related_name='companies') starter = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='companies', ) views = models.PositiveIntegerField(default=0) def __str__(self): return self.name def get_absolute_url(self): return reverse('company_detail', args=[str(self.id)]) def get_recent_reviews(self): return self.reviews.order_by('-created_at') def get_last_ten_reviews(self): return self.reviews.order_by('-created_at')[:10] class Review(models.Model): RATING_CHOICES = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) STAY = ( ('less than 6 months', 'less than 6 months'), ('6 months', '6 months'), ('10 months', '10 months'), ('12 months', '12 months'), ('More than 1 year', 'More than 1 year'), ) YES_NO = ( ('Yes', 'Yes'), ('No', 'No'), ) SECURITY = ( ('100%', '100%'), ('75%', '75%'), ('50%', '50%'), ('25%', '25%'), ('0%', '0%'), ('Still waiting', 'Still waiting'), ) created_at = models.DateTimeField(auto_now_add=True) … -
I want to serializer Task ID with the Bug Details
My Django Models I want to serialize "Task Id" from "Task" Table when I serialize Bug Model. When I serialize Bug I also want it's associated "taskId" as a JSON Response. Models --> Task Model, Bug Model, TaskBug Model (One to One) Task Model TASK_STATUS = ( ('Not Assigned','Not Assigned'), ('Assigned','Assigned'), ('Completed','Completed'), ('Ready to Check', 'Ready to Check'), ('Bug Found', 'Bug Found'), ) taskid = models.IntegerField(primary_key=True) taskname = models.CharField(max_length=50) task_status = models.CharField(max_length=50,choices=TASK_STATUS,default='Not Assigned') description = models.TextField() assignee = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True, blank=True, related_name='tassignee') assigner = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True, blank=True, related_name='tassigner') project_id = models.ForeignKey(Project, on_delete=models.CASCADE, null=True, blank=True) class Meta: ordering = ('taskid',) def __str__(self): return self.taskid,self.taskname Bug Model class Bug(models.Model): STATUS = ( ('Assigned','Assigned'), ('Reassigned','Reassigned'), ('Fixed','Fixed'), ) SEVERITY = ( ('Critical','Critical'), ('High','High'), ('Medium','Medium'), ('Low','Low'), ) PRIORITY = ( ('High','High'), ('Medium','Medium'), ('Low','Low'), ) bugid = models.IntegerField(primary_key=True) bugname = models.CharField(max_length=50) description = models.TextField() status = models.CharField(max_length=50, choices=STATUS,default='assig') screenshot= models.URLField(max_length=200) priority = models.CharField(max_length=50,choices=PRIORITY,default='M') severity = models.CharField(max_length=50,choices=SEVERITY,default='M') reporter = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True, blank=True,related_name='breporter') assignee = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True, blank=True,related_name='bassignee') bug_date = models.DateField(auto_now_add=True) due_date = models.DateField() TaskBug Model class TaskBug(models.Model): task_id = models.ForeignKey(Task,on_delete=models.CASCADE, null=True, blank=True) bug_id = models.ForeignKey(Bug, on_delete=models.CASCADE, null=True, blank=True) class Meta: unique_together = [['task_id','bug_id']] ordering = ('task_id',) def __str__(self): return str(self.task_id) -
Resolving TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
A few people on Stack Overflow have already discussed this problem but none of the answers were any help to me. This is post_2 post_2 = Post(title = 'Dark Knight', content='Batman was amazing in the Dark Knight', author_id=User.id) This is the contents of models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title When I do >>> post_2.save() I get the error TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' Here is the full error Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\HP\project2_env\lib\site-packages\django\db\models\base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "C:\Users\HP\project2_env\lib\site-packages\django\db\models\base.py", line 779, in save_base force_update, using, update_fields, File "C:\Users\HP\project2_env\lib\site-packages\django\db\models\base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\HP\project2_env\lib\site-packages\django\db\models\base.py", line 908, in _do_insert using=using, raw=raw) File "C:\Users\HP\project2_env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\HP\project2_env\lib\site-packages\django\db\models\query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\HP\project2_env\lib\site-packages\django\db\models\sql\compiler.py", line 1334, in execute_sql for sql, params in self.as_sql(): File "C:\Users\HP\project2_env\lib\site-packages\django\db\models\sql\compiler.py", line 1278, in as_sql for obj in self.query.objs File "C:\Users\HP\project2_env\lib\site-packages\django\db\models\sql\compiler.py", line … -
add dicitonaries type data to dropdown (select form element)
i have a code to list all data from database to dropdown def makeDictFactory(cursor): columnNames = [d[0] for d in cursor.description] def createRow(*args): return dict(zip(columnNames, args)) return createRow def list_all_table(request): import cx_Oracle dsn_tns = cx_Oracle.makedsn('', '', sid='') conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns) c = conn.cursor() c.execute("select table_name from all_tables") c.rowfactory = makeDictFactory(c) for rowDict in c: context = { 'obj2':rowDict } #database_table = c.fetchall() return render(request,'define_segment.html',context) this is the html code <div class="btn-group"> <select style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> {% for table in obj2 %} <option>{{ table.table_name }}</option> {% endfor %} </select> </div> how to pass the parameter to the obj2 in html , i have feeling that my views is wrong and i need help to fix it , thankyou P.S : I need this views.py to work to make a dependent dropdown from this code -
How to make follower-following system with django model
I'm a student studying django rest framework I'm making a simple sns with django rest framework I need follower-following system. So, I tried to make it but there is some trouble Fist this is my user model with AbstractBaseUser and PermissionsMixin class User(AbstractBaseUser, PermissionsMixin): user_id = models.CharField(max_length=100, unique=True, primary_key=True) name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) followers = models.ManyToManyField('self', related_name='follower',blank=True) following = models.ManyToManyField('self', related_name='following',blank=True) profile_image = models.ImageField(blank=True) the field followers is people who follows me and following is whom i follow When i add following with this APIView class class AddFollower(APIView): permission_classes = [IsAuthenticated, ] def post(self, requset, format=None): user = User.objects.get(user_id=self.request.data.get('user_id')) follow = User.objects.get(user_id=self.request.data.get('follow')) user.following.add(follow) user.save() follow.followers.add(user) follow.save() print(str(user) + ", " + str(follow)) return JsonResponse({'status':status.HTTP_200_OK, 'data':"", 'message':"follow"+str(follow.user_id)}) The user_id is me and the follow is whom i want to follow I want to add follow to user_id's following field and add user_id to follow's followers field But it does not work What i want for result is like this (with user information api) { "followers": [], "following": [ "some user" ], } some user's user info { "followers": [ "user above" ], "following": [ ], } But real result is like this { "followers": [ "some … -
Why does querying "green bay" not work when "green" or "bay" does in my Django view?
Here is my view: def search(request): if request.method == 'GET': try: q = request.GET.get('search_box', None) s_or_l = request.GET.get('s_or_l', None) p_class = request.GET.get('p_class', None) if p_class: posts = Listing.objects.filter(title__contains=q, is_live=1, sale_or_lease=s_or_l, property_class=p_class) | \ Listing.objects.filter(street_address__contains=q, is_live=1, sale_or_lease=s_or_l, property_class=p_class) | \ Listing.objects.filter(city__contains=q, is_live=1, sale_or_lease=s_or_l, property_class=p_class) | \ Listing.objects.filter(state__contains=q, is_live=1, sale_or_lease=s_or_l, property_class=p_class) else: posts = Listing.objects.filter(title__contains=q, is_live=1, sale_or_lease=s_or_l) | \ Listing.objects.filter(street_address__contains=q, is_live=1, sale_or_lease=s_or_l) | \ Listing.objects.filter(city__contains=q, is_live=1, sale_or_lease=s_or_l) | \ Listing.objects.filter(state__contains=q, is_live=1, sale_or_lease=s_or_l) return render(request, 'search/results.html', {'posts': posts, 'q': q}) except KeyError: return redirect('home') For a property with a city set to "Green Bay" the following searches work as intended: green bay Green Bay but green bay <-- does not work. Why is this? How can I fix it? -
Loading an image in Phaser using django web server
Basically, Django GET request cannot locate my file path. I've read through all the other questions like: how to load a image using phaser but I still don't have an answer. Here's a breakdown of the file locations: project->app->static-> .js and .html files project->app->static->assets-> .png file HTML: home.html {% load static %} <!DOCTYPE html> <html> <meta charset="UTF-8"> <head> <title>Dice Game</title> <link rel="stylesheet" href="{% static 'home.css' %}" type="text/css"> <script type="text/javascript" src='{% static "phaser.js" %}'></script> <script type="module" src='{% static "dice_game.js" %}'></script> </head> <body> <div id="dice-game"></div> <div class="game_box"> <h1>Hello</h1> </div> <p>{{request.user}}</p> </body> </html> JS: dice_game.js import {Dice, Dice_Roll} from './dice.js'; var new_die = new Dice(2); var config = { type:Phaser.AUTO, parent:'dice-game', // populates the div tag class in the html width:800, height:600, physics: { default:'arcade', }, scene: [Dice_Roll] } var game = new Phaser.Game(config); dice.js export class Dice{ constructor(num) { this.num = num; this.state = true; } } export class Dice_Roll extends Phaser.Scene { constructor() { super({key:"Dice_Roll"}); } preload() { this.load.image('die', "assets/blank_die.png"); } create() { this.add.image(400, 300, 'die'); } } PYTHON: urls.py from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path from pages.views import home_view, about_view from products.views import product_detail_view, product_create_view urlpatterns = [ path('admin/', admin.site.urls), … -
How to filter object from model User into list
I am trying to make a list from users I filter, which is here: User.objects.filter(groups__name='Staff') output which I want it something like list_of_usernames = [adam, joe, natalie] In list has to be username of the user. Can some please help me to write that query? I tried something to_list but it did not work out for me. -
How to add to ManyToMany when getting "no attribute" error?
Using a form, I'm trying to add items to the manytomany field questions of a Quiz object after first getting a queryset of the questions I want to add. I save the ModelForm but when I add the item, I get an AttributError: 'function' object has no attribute 'questions' Previously I was able to create a Quiz object with 3 random questions using a save method in the model. However, I don't see a way to add 3 questions from a particular queryset using only the model views.py def choose(request, obj_id): """Get the id of the LearnObject of interest""" """Filter the questions and pick 3 random Qs""" my_qs = Question.objects.filter(learnobject_id=obj_id) my_qs = my_qs.order_by('?')[0:3] if request.method == 'POST': form = QuizForm(request.POST) if form.is_valid(): new_quiz = form.save for item in my_qs: new_quiz.questions.add(item) new_quiz.save() return HttpResponseRedirect('/quizlet/quiz-list') else: form = QuizForm() return render(request, 'quizlet/quiz_form.html', {'form': form}) and models.py class LearnObject(models.Model): """model for the learning objective""" code = models.CharField(max_length=12) desc = models.TextField() class Question(models.Model): """model for the questions.""" name = models.CharField(max_length=12) learnobject = models.ForeignKey( LearnObject, on_delete=models.CASCADE, ) q_text = models.TextField() answer = models.CharField(max_length=12) class Quiz(models.Model): """quiz which will have three questions.""" name = models.CharField(max_length=12) questions = models.ManyToManyField(Question) completed = models.DateTimeField(auto_now_add=True) my_answer = models.CharField(max_length=12) class QuizForm(ModelForm): … -
Django: How to create a new custom user with custom registration form
I am trying to make a custom registration form in Django, using HTML and CSS and not Django's form.as_p. I have the following code in views.py: def register(request): if request.POST: username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password_confirm = request.POST['password-confirm'] if(valid_form(username, email, password, password_confirm)) { #create the new user } else { #send some error message } return render(request, 'index.html') I have my own function valid_form to check if the form fields entered by the user are valid. However, I am not sure how I can create the new user using a custom User Model. In all of the code examples regarding registration forms I have seen something like this: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('main-page') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) Where form.save() is used to create the new user. I have the following model for a user in models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=70, null=True) How can I create a new CustomUser after validating form data? Any insights are appreciated. -
Not able to resolve MultiValueDictKeyError at ['documents']
I want to upload an excel file to the server but I'm getting an error as MultiValueDictKeyError at ['documents'] in the below mentioned code. views.py def index(request): if request.method == 'POST': uploaded_file = request.FILES['document'] print(uploaded_file.name) print(uploaded_file.size) return render(request, "polls/upload.html") upload.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="file" name="document"> <button type="submit">Upload</button> </form> I want to be able to upload the file but I'm getting an error as MultiValueDictKeyError at ['documents']. Can anyone please tell me what is wrong with the code? -
How can i add intcomma in django messages template
After add extra_tags='safe' in views , and {{ messages|safe }} in templates, how can i add |intcomma, humanize, in message ??? -
How to submit a form from a Django Modal
I am trying to upload Videos to my Django website using a modal. Currently when I try to submit the form I get the error 'NoneType' object has no attribute 'is_ajax' I have been going through Django tutorials as well as bootstrap/html/ guides by I can not find a clear answer on why the form is not submitting. base.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Our style.css --> {% load static %} <link rel="stylesheet" href="/static/VR360/style.css?{% now "U" %}"/> <title>Umbra</title> </head> <body> <ul> <li><a href="#login">Login</a></li> <li><a href="{% url 'upload-videos' %}">Upload Videos</a></li> <li><a href="{% url 'homepage' %}">Home</a></li> </ul> <!-- Everything that extends base.html, the code will be "inside" these two block content commands--> <div id="page-wrap"> {% block content %} {% endblock content %} </div> </body> </html> upload_videos.html {% extends "VR360/base.html" %} {% block content %} <h1>Upload Videos</h1> <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <form method="post" enctype="multipart/form-data"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> {% csrf_token %} {{ form.as_p }} </div> … -
How can I display a Bootstrap Toggle with a dynamically value using Django?
I'm doing an update action where the user click over an element in a table and then change the value by switching a bootstrap toggle, but I don't know how and where should I do the change. This is my code: First, the user can click over the element, sending the Id: <div class="btn fa-hover col-md-3 col-sm-4 col-xs-12" data-toggle="modal" onclick='wordEditModal({{key.id}})' data-target="#wordUpdateModal"><i class="fa fa-edit"></i> Then, it calls to wordEditModal function, to make a request to the endpoint: url:'/socialanalyzer/dictionary_edit_modal/', It returns the polarity of the word clicked and simultaneously in the HTML, a modal is opened, here I should display the value returned with the bootstrap toggle: <form method="get" novalidate> {% csrf_token %} <fieldset> <div class="form-group"> <!-- Now, this bootstrap toggle always display Positive value, I want that it display dynamically from the endpoint the value--> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="polaridad">Polarity:</label> <input id="toggle-polarity" checked type="checkbox" data-on="Positive" data-off="Negative" data-onstyle="success" data-offstyle="danger" data-width="100"> </div> <br/><br/><br/> <div class="modal-footer"> <input class="btn btn-success" type="submit" onclick='wordUpdate()' value="Guardar" /> <button type="button" class="btn btn-default" onclick="" data-dismiss="modal">Close</button> </div> </fieldset> </form> This is my ajax function: function wordEditModal(wordId) { $.ajax({ url:'/socialanalyzer/dictionary_edit_modal/', type: 'GET', data: { word_id: wordId },success: function(data) { if (data.data.code==200) { // This is what I tried, but didn't work … -
add an icon/div to the preview images when onactivatefile is fired (Filepond)
Background: I have a django project where a user can upload multiple images, and one of them will be the main image. I am using Filepond to upload and optimize images. The order that Filepond uploads files is not always the same as the order of files selected by a user. Because of that, I try to provide an option for user where a user clicks on a file (in this case, showed as a preview image) and the clicked file will become the main image. I used the following code to log user-clicked image as the main image in the server-side and it works. onactivatefile: (file) => { console.log(file); console.log('mainimage'); filename = file.filename; console.log(filename); $.ajax({ type: "POST", url: "{% url 'ajax_mainimage' pk=sellingitem.pk %}", data: {pk:"{{sellingitem.pk}}", 'filename':filename, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", }); }, Question: To provide a better experience for the user, I try to achieve the following: when a user clicks one of the preview images, say image A, a text ("this is your main image") or an icon shows up in the image A. How can I do this or something similar? Thanks! -
Problems with inline django modelformset?
I am learning to implement django inlineformset and I am facing the following error. On the client side, I am using the django-dynamic-formset jquery plugin. But when I render the formset, I see 'add another or remove option appear multiple times. This is what I tried so far.This error happened when I switched to formset in the instead of form. forms.py class BaseSkillFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseSkillFormSet,self).__init__(*args, **kwargs) self.queryset = Skill.objects.exclude(skill_name__isnull=True) class BaseWorkExperienceFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseWorkExperienceFormSet,self).__init__(*args, **kwargs) self.queryset = WorkExperience.objects.exclude(company_name__isnull=True) class BaseEducationFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseEducationFormSet,self).__init__(*args, **kwargs) self.queryset = Education.objects.exclude(name__isnull=True) class SkillForm(forms.ModelForm): class Meta: model = Skill fields=('skill_name','level_of_proficiency',) class WorkExperienceForm(forms.ModelForm): class Meta: model = WorkExperience exclude = ('user',) widgets = { 'start_date': DateInput() } class EducationForm(forms.ModelForm): class Meta: model = Education exclude = ('user',) widgets = { 'start_date': DateInput() } class CollectionCreate(UpdateView): model = UserProfile template_name = 'accounts/user_profile_form.html' form_class = UserProfileForm success_url = None def get_context_data(self, **kwargs): data = super(CollectionCreate, self).get_context_data(**kwargs) if self.request.POST: data['formset'] = SkillFormSet(self.request.POST) data['formset1'] = WorkExperienceFormSet(self.request.POST) data['formset3'] = EducationFormSet(self.request.POST) return data else: print('object',self.object) data['formset'] = SkillFormSet() data['formset1'] = WorkExperienceFormSet() data['formset3'] = EducationFormSet(instance=self.object) return data SkillFormSet = inlineformset_factory( UserProfile, Skill, formset=BaseSkillFormSet, fields=['skill_name', 'level_of_proficiency'], can_delete=True,extra=1 ) WorkExperienceFormSet = inlineformset_factory( UserProfile, WorkExperience, formset=BaseWorkExperienceFormSet, fields=['company_name', 'start_date','end_date','work_description'], can_delete=True,extra=1, … -
I am having an error "Not Found: /painel/all/list.css" when I ran my django app
I am creating my first Django project, and I wanted to create a page with a picture as the background. I have followed some tutorials on the internet, but then when I ran my code, it just shows the html file, and in the terminal is "Not Found: /painel/all/list.css" I have already tried to see if it was the path of "static" file, and maybe it still is and I did it wrong, but I don't know what else to do. I have read some questions here in stack overflow, but I couldn't find the mistake in mine. there is the settings.py """ Django settings for sitetcc project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o+7e$z&!3*#r3%*n$3(l7a3+(u18sj@33y(5p4_3*&*4l_lpfw' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "sitetcc/static"), … -
How to make two search bar in django?
I'm building a simple app that will allow users to search for a given value. for example, users search for "Industry" and "revenue".I want to know how to make two search bar works together. thanks in advance. views.py def app(request): all_details=Company_Details.objects.all() query=request.GET.get("q") if query: all_details=all_details.filter( Q(industry__icontains=query)| Q(employees_number__icontains=query)| Q(revenue__icontains=query) ).distinct() paginator=Paginator(all_details,3) page=request.GET.get('page') try: all_details=paginator.page(page) except PageNotAnInteger: all_details=paginator.page(1) except EmptyPage: all_details=paginator.page(paginator.num_pages) context={ 'all_details':all_details } return render(request,'icpapp/app.html',context) app.html <div class="search"> <form method='GET' action=""> <input type="text" name='q' placeholder="Industry " list="Industry" class="searchterm" value='{{request.GET.q}}' /> <datalist id="Industry"> <option value="software"> <option value="Security"> </datalist> <input type="text" name='q' placeholder="revenue " list="revenue" class="searchterm" value='{{request.GET.q}}' /> <datalist id="revenue"> <option value="20M"> <option value="50M"> </datalist> <button type='submit' value='Search' class='dfg' />search</button> </form> </div> {% if request.GET.q%} {% for Company_Details in all_details %} <h1>{{ Company_Details.company_name}}</h1> <h1>{{Company_Details.industry}}</h1> <h1>{{Company_Details.revenue}}</h1> <h1>{{Company_Details.employees_number}}</h1> {%endfor%} {%else%} <h3>start searching</h3> {%endif%} -
How to use root directory as the base url to render a html page?
I added name tags in my html pages using '{% url 'blog-home' %}' tag. If i try to access it through navigation bar from root directory, it is opening correctly at localhost:8000/blog but when i again try to access it through navigation bar, it is taking relative path and redirects me to localhost:8000/blog/blog . # views.py def blog_main_page(request): return render(request, 'blog.html') # urls.py urlpatterns = [ path('', views.blog_main_page, name='blog-home'), ] # urls.py (Main App) urlpatterns = [ path('', include('homepage.urls')), path('blog/', include('blog.urls')), ] I expect the resulting url to be localhost:8000/blog but not localhost:8000/blog/blog