Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert datetime.date to django compatible date
I am reading data from an excel file and the date is being read in the following format: 'Date': datetime.date(2020, 2, 3) #yyyy-mm-dd whereas the Django allows the following date format: date: "2020-02-03T06:06:39.548Z" How can I convert the datetime.date to the compatible date format ? -
Unit Testing in Python Djnago
I am using Django==3.0.3 djangorestframework==3.11.0 python ==3.6.8 I want to write unit testing for API and no need to use any database(no need of mock database) that mean I want to mock the database call and write unit test cases how can i write which property is used for this Showing my api @api_view(['POST']) @permission_classes([IsAuthenticated]) def employee_entry(request): try: login = User.objects.get(pk=request.user.id) validationmsg = '' emp_data = request.data if not emp_data: validationmsg = validation["FDP15"] elif emp_data["EmployeeName"] is None or emp_data["EmployeeName"] == '': validationmsg = validation["FDP1"] elif emp_data["EmployeeCode"] is None or emp_data["EmployeeCode"] == '': validationmsg = validation["FDP2"] elif Employee.objects.filter(EmployeeCode=emp_data["EmployeeCode"]).count() > 0: validationmsg = validation["FDP3"] if validationmsg != '': return Response({msg: validationmsg}, status=status.HTTP_400_BAD_REQUEST) employee = Employee( EmployeeName=emp_data["EmployeeName"], EmployeeCode=emp_data["EmployeeCode"], Security=emp_data["Security"], CreatedDate=date.today(), CreatedUser=login, ) employee.save() if emp_data["Security"] == 1: device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"])) employee.Device.set(device) elif emp_data["Security"] == 0: device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"]), DefaultAccess=True) employee.Device.set(device) return Response({"EmployeeId": employee.EmployeeId}, status=status.HTTP_200_OK) except(KeyError, TypeError, ValueError) as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP21"]}, status=status.HTTP_400_BAD_REQUEST) except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) -
Django form validation with FileField
I am having some trouble getting a file to post via a form using generic class-based view CreateView. Below is what i have so far. I am not quite sure how to handle the file and if request.FILES is getting the file being posted or if there is something else i need to be doing to capture the file information in the form. I have tried following the docs, however no luck in getting something working. File uploads as a blank field. views.py # Create class FileUploadCreateView(BSModalCreateView): template_name = 'fileupload/create-file.html' form_class = FileUploadModelForm success_message = 'Success: File was uploaded.' success_url = reverse_lazy('files_list') # Add required field my_user prior to posting form def form_valid(self, form): form = FileUploadModelForm(self.request.POST, self.request.FILES) self.object = form.save(commit=False) self.object.my_user = self.request.user self.object.file_status = 'ready' return super().form_valid(form) -
How to save search query result into the model with Django?
This is for revert/rollback the table. I have a query like this: query = Table.objects.all() it takes all entries in the Table. I will delete it later: Table.objects.all().delete() Now I want to save query into Table. How can I do that? -
Django failed to read static files from Azure Blog storage
Here is my application settings.py, command "python manage.py collectstatic" works fine and pushing static files to azure STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'dist', 'static'), ] STATICFILES_STORAGE ='backend.custom_azure.AzureStaticStorage' DEFAULT_FILE_STORAGE = 'backend.custom_azure.AzureMediaStorage' AZURE_ACCOUNT_NAME = os.environ['AZURE_ACCOUNT_NAME'] AZURE_ACCOUNT_KEY = os.environ['AZURE_ACCOUNT_KEY'] AZURE_CUSTOM_DOMAIN = os.environ['AZURE_CUSTOM_DOMAIN'] STATIC_LOCATION = 'static' STATIC_URL = f'http://xxxxxxxx.blob.core.windows.net/static/' AZURE_LOCATION = os.environ['AZURE_LOCATION'] AZURE_CONTAINER = os.environ['AZURE_CONTAINER'] MEDIA_LOCATION = "media" MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' While running the application server looking for the static files and fails, server looking for different path, I can see static files in Azure [10/Nov/2020 05:24:47] "GET /static/js/app.fa77985a.js HTTP/1.1" 404 77 [10/Nov/2020 05:24:47] "GET /static/css/chunk-vendors.102171f9.css HTTP/1.1" 404 77 [10/Nov/2020 05:24:47] "GET /static/css/app.0f5f9b8e.css HTTP/1.1" 404 77 [10/Nov/2020 05:24:47] "GET /static/js/chunk-vendors.56f4d0fa.js HTTP/1.1" 404 77 Following the doc available at https://medium.com/@DawlysD/django-using-azure-blob-storage-to-handle-static-media-assets-from-scratch-90cbbc7d56be -
How to get the object type and name on Django
I have this obj details on my Django context debug u'non_homepage_obj': <Organisation: text-org>, This is the context related to it 'non_homepage_obj': obj.primary_publisher, How to get the <Organisation: text-org> into string, which i can put the Organisation or the name of Organisation into use later on? I already tried str(obj.primary_publisher) but it's only get the text-org, and not passing the Organisation. Thanks -
Django Calculation inside HTML
I wanted to do something simmilar to this suing django. but somehow i it doesn't work. how do i fix it? for statik in statistik{ print(statik*total/100) } Is there any documentation regarding what I'm trying to implement to my django app? Thank you Here's the HTML : {% if statistics %} {% for statik in statistics|slice:":4" %} <div class="mb-3"> <div class="small text-gray-500">{{ statik.name }} <div class="small float-right"><b>{{ statik.voters }} of {{ total }} Voters</b></div> </div> <div class="progress" style="height: 12px;"> <div class="progress-bar bg-success" role="progressbar" style="width: {{ statik.voters * total/100 }}%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> {% endfor %} {% else %} <p>END TABLE</p> {% endif %} -
How do I query that spans multiple relationships?
Here's a simplified version of my model class: class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class UserProfile(models.Model): user = models.OneToOneField(User, related_name = 'profile') first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) following = models.ManyToManyField(User, related_name = 'followed_by', blank=True, through='FollowingRelation') class FollowingRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) I'd like to query all rows from BlogPost that have been created by the session user, plus all other posts created by the users that the sessionUser is following, but has a timestamp greater than or equal to the timestamp when the session user started following. -
Refused to apply style from because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
after adding build folder(from reactjs) to my django backend folder. I am getting this error while running the surver. another similar error is : Refused to execute script , because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. i have added the path of build folder in the templates section in the setting.py file..here is the code: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] can anyone please help me fix this?? -
Django-crontab is not working on in linux ec2 instance
I'm trying to set up cron jobs in my django application on a ec2 instance(linux). Everything is working fine, I tried python3 manage.py cron add python3 manage.py cron show python3 manage.py cron remove everything works just fine But when I start the apache server, and load the page, I'm getting 500. From the error logs I found that django_crontab module was not found. But it's still there and I've installed it in the virtual environment too (I've double checked with pip3 freeze). I also tried sudo service cron start which didn't show me anything and didn't make any difference. What could be the possible issue here? -
Cannot read csv files uploaded using pandas in Djnago
I have the following view defined in my Django views:- def csv_file_upload(request): if request.method == "POST" and request.FILES['file_upload']: registry = request.POST.get('reg_select').lower() csv_file = request.FILES['file_upload'] data = pd.read_csv(csv_file, delimiter="\|\|") print(data.head()) return render(request, "csv_file_upload.html", {}) But the pd.read_csv part is giving me this error:- cannot use a string pattern on a bytes-like object The sample csv file that I have is like this: Col_A||Col_B||Col_C A0||B0||C0 A1||B1||C1 The same file I can read using pd.read_csv() without using Django and do no get this error. Why is this error being caused when using Django? -
unable to use link to the admin page in django
i am using django 3.0.8 on python 3.7 and every time use the link to the admin page. i get this: this is the cmd console after i enter the admin page. this is the web page error my urls.py file and my settings.py file i am not finding any solutions online and any help would be appreciated. P.S i am using the database django comes with. the sqlite3 one. -
How do I initialize a django form with the previous input in a class based view?
It displays a form on the top and when you submit it, it will only show some of the Offer instances that fits the filters. It works fine, but every time I submit it, the form returns to the initial value. How can I stop that? My form uses GET and the view is class-based. Also, the __init__ in the form doesn't seem to be working. views.py class Search(ListView, FormMixin): model = Offer template_name = 'search.html' paginate_by = 20 form_class = SearchForm def get_queryset(self): self.form = SearchForm(self.request.GET) if self.form.is_valid(): data = self.form.cleaned_data qs = Offer.objects.all() if data['book'] != '0': qs = qs.filter(book_id=data['book']) qs = qs.filter(worn_degree__in=data['min_worn_degree']) qs = qs.filter(note_degree__in=data['min_note_degree']) return qs else: return Offer.objects.all() search.html {% extends 'base_generic.html' %} {% block content %} <form method="get"> {% csrf_token %} <table> {{ form.as_table }} </table> <br> <input type="submit" value="검색"> </form> {% if object_list %} {% for object in object_list %} <p>{{ object.book.title }}</p> <p>{{ object.seller }}</p> {% endfor %} {% else %} <p>There are no offers.</vp> {% endif %} {% endblock %} forms.py class SearchForm(forms.Form): def __init__(self, *args, **kwargs): super(SearchForm, self).__init__(*args, **kwargs) self.book = '0' self.min_worn_degree = 'abc' self.min_note_degree = 'abc' BOOK_CHOICE = tuple([('0', '모두')] + [(book.id, book.title) for book in Book.objects.all()]) book … -
Form booleanfield does not appear in request.POST data
I tried printing out all (key,value) pairs in a request.POST to extract the form data. I notice that a BooleanField, if not checked (i.e. set to True), is not included in request.POST. This is true even if the BooleanField is set with required=True. Is it possible to force the (key,pair) to be sent? For example, in this form below, if applied field is not checked when rendered, request.POST should still include applied off? When applied is checked, request.POST includes applied on. But without being checked, applied is not part of request.POST data. class ItemModifierForm(forms.Form): applied= forms.BooleanField(label='Trait A', required=True) -
Django: prefetch related: for loop: based on how we call for loop, the number of sql call varies
In django i am trying to understand prefetch: I have two for loop scenarios after prefetch symbollist = SymbolList.objects.prefetch_related('some_related_name')[0:10] for i in range(0,symbollist.count()): print(symbollist[i].some_related_name) Now it calls sql N+1 times where as symbollist = SymbolList.objects.prefetch_related('some_related_name')[0:10] for symbol in symbollist: print(some_related_name) this will call only two sqls Why so -
Django Can I change the Receive Charset specific View?
settings.py DEFAULT_CHARSET = 'UTF-8' views.py class OrderResult(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): payload = request.data <<---- some string broken *** save to database i'd like to receive data with 'euc-kr' only in the above View. Is it impossible? I can't find it. -
How to fix find and Field 'id' expected a number but got '' error
I am trying to add a like button to my posts in a Django Project. I have made a model for the likes and included a value for it. In the template the post_id should be reflected in the views but for some reason it is showing an error. So, I have followed all the steps correctly but I am getting error: ValueError at /blogs/like Field 'id' expected a number but got ''. Here is the models.py class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') ...................................... @property def num_likes(self): return self.liked.all().count() LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) Here is the views.py def like_post(request): user=request.user if request.method=='POST': post_id=request.POST.get('post_id') post_obj= Post.objects.get(id=post_id)<--------------- Error highlighted in this line if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_created(user=user,post_id=post_id) if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' like.save() return redirect('blog:post_list') Here is the template: <form action="{% url 'blog:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value='{{obj.id}}'> {% if user not in obj.liked.all %} <button class="ui button positive" type="submit">Like</button> {% else %} <button class="ui button negative" type="submit">Unlike</button> {% endif %} <strong>{{ obj.like.all.count }} … -
Django - Add the same set of objects to a queryset using a ManyToMany field
I have pizzas and I have toppings. class Pizza(ModelBase): name = models.CharField(max_length=255) toppings = models.ManyToManyField('Topping', blank=True, related_name='pizzas') class Topping(ModelBase): name = models.CharField(max_length=255) Let's suppose I want to add the toppings Tomato and Cheese to every pizza in my database. At the moment I can do it with a nasty for loop: toppings = Toppings.objects.filter(Q(name='Tomato') | Q(name='Cheese')) for pizza in Pizza.objects.all(): pizza.toppings.add(*toppings) Is there a way to achieve the same thing without having to loop all the pizzas? Maybe using the through table that Django creates? I know that I can delete the toppings from all the pizzas using the following query: Pizza.toppings.through.objects.filter(topping__in=toppings).delete() but I haven't been able to add toppings to multiple pizzas without the for loop. -
Why is one text element of a table not aligning with the rest?
I'm making a game based off of a gameshow with Django, and want the users to be able to select a specific episode to play. The page in question is after the users have selected a year from the database, when they select the month from which they want to play. For some reason, no matter which year is selected, the month of March is always not aligned with the rest of the text. This occurs if March is the first, second, or third available month. I have not styled it differently from the others, and when I click inspect it randomly aligns with the rest (pictures attached). I've attached the code from episode_month.html and main.css. If anyone could help me align this month or give insight as to why it's above the others I'd appreciate it--it's been driving me crazy! episode_months.html: {% extends "game/base.html" %} {% load static %} {% block content %} <div class = "mode">Available Months</div> <div class = "mode_info">{{ year }}</div> <table class = "board"> {% for month_group in months %} <tr class = "row"> {% for month in month_group %} {% if month != "" %} <th class = "tile-months board_cat"> <a class = board_month … -
Cmd is not finding my files. I can see them in file explorer, but am unable to see them or access them in cmd
I am unable to access bookbuddy or activate my python virtualenv. The problem is not specific to this Project-BookBuddy directory. There are strange and inconsistent results in other directories as well. I recently synced with oneDrive. IDK if that has anything to do with this. -
Django + chart.js: plot with django Queryset data
I am across a problem that I cannot handle. I passing queryset data from a django view to its corresponding template and I want to use this data to plot a graph with chart.js I am trying to achieve this without using Ajax requests. However, when I try to acquire the queryset data with javascript to pass it in chart.js it renders an error. Here is what I have done in html: <div id="default_data"> <p> {{ default_items }} </p> </div> <div id="labels"> <p>{{ labels }} </p> <div class="col-lg-6"> <div id="tag3" class="card-footer small text-muted">{% trans 'ITEMS WITH HIGHEST NUMBER OF SALES (3 MONTHS)' %}</div> <div class="bar-chart block"> <canvas id="myChart3" height="90"></canvas> </div> </div> and here is what labels and default_data render: <QuerySet [58.0, 62.0, 74.0, 60.0, 16.0, 1.0, 1.0, 1.0, 1.0, 2.0]> <QuerySet ['372750', '372600', '372650', '372700', '372150', '289807', '289922', '289840', '289923', '372310']> and javascript: <script> var ctx3 = document.getElementById('myChart3').getContext('2d'); var labels = document.getElementById("labels"); var myChart3 = new Chart(ctx3, { type: 'bar', data: { labels: labels, datasets: [{ label:'références avec nombre de ventes élevé', data: default_data, label: '# of Votes', borderWidth: 1, }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> I don't … -
paginate by a number of objects django
So pagination isn't working even without initiating django-filters from templates, I'm not able to paginate by the number of objects I want, it's showing all of them at once *Note: I'm not saying both should work together(pagination and django-filter), just that I wanna fix the pagination views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) template <div class='card'> {% for m in filter.qs %} <div class='year'>{{m.Year}}</div> <div class='song_name'>{{m.song}}</div> {% endfor %} </div> -
What is the correct way to show multiple size HTML form fields for different resolutions
I have a Django form I am rendering manually, using the widget_tweaks django app, and bootstrap 4. Bootstrap has utilities to show or hide elements based on the resolution, and I thought this would be ideal to control how a contract form displays on desktop verse a mobile device. I included each form field twice, but failed to realize that even though it is not shown on the screen, it is still present and active. As such, my form was not being submitted, and worse the error that a form field needs to be filled in was also not visible. What is the correct way to resize form fields for different resolutions, or to deactivate form fields if they are not shown on screen? This was my attempt: <form method="POST">{% csrf_token %} <table class="table table-borderless"> <tr class="d-flex"> <td class="col-2 d-none d-sm-block"><b>Name</b></td> <td class="col-10 d-none d-sm-block">{% render_field form.name class+="form-control" placeholder="Your Name" %}</td> </tr> <!-- <tr class="d-flex d-sm-none"> <td class="col-4 d-sm-none"><b>Name</b></td> <td class="col-8 d-sm-none">{% render_field form.name class+="form-control" placeholder="Your Name" %}</td> </tr>--> <tr class="d-flex"> <td class="col-2 d-none d-sm-block"><b>E-mail</b></td> <td class="col-10 d-none d-sm-block">{% render_field form.email class+="form-control" placeholder="Your E-mail" %}</td> </tr> <!-- <tr class="d-flex d-sm-none"> <td class="col-4 d-sm-none"><b>E-mail</b></td> <td class="col-8 d-sm-none">{% render_field form.email class+="form-control" placeholder="Your … -
how to pivot with django pandas using foreign keys
I am using django-panda to make a dynamic table and I have achieved it, the problem I have is that I would like to add more rows to the table using foreign key relationships, in the documentation it says: "to span a relationship, just use the field name of related fields in models, separated by double underscores, "however this does not work with to_pivot_table. I did a test with to_dataframe and here the logic if it gives results, but what I need is to implement it in the pivot these are my models: class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,related_name='student') quizzes = models.ManyToManyField(Quiz, through='TakenQuiz') interests = models.ManyToManyField(Subject, related_name='interested_students') def get_unanswered_questions(self, quiz): answered_questions = self.quiz_answers \ .filter(answer__question__quiz=quiz) \ .values_list('answer__question__pk', flat=True) questions = quiz.questions.exclude(pk__in=answered_questions).order_by('text') return questions def __str__(self): return self.user.username class TakenQuiz(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='taken_quizzes') quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='taken_quizzes',verbose_name='Examen') score = models.FloatField() date = models.DateTimeField(auto_now_add=True) objects = DataFrameManager() and my views class ResultadosTotales(ListView): def get(self,request,*args,**kwargs): examen=TakenQuiz.objects.all() qs=TakenQuiz.objects.all() df2=taken.to_dataframe(['student__user__first_name' ,'quiz', 'score'], index='student') print(df) #here I did the test with the related attribute and if it works rows = ['student','student__user__first_name'] #Here it does not work even though the documentation uses the same logic rows = ['student'] cols = ['quiz'] print(df2) pt … -
Django - saving an already created file to file.field()
My program essentially creates an excel file by integrating an api and webscraping It then puts that excel file into a folder. Then, I want to save that file to a Django model file field so that I can access it through the web portal. Can somebody help me find documentation that would help with this? Or perhaps just give me a general direction of how to approach this problem? Thank you! TLDR Step 1: CREATE EXCEL FILE Step 2: STORE EXCEL IN SEPARATE FOLDER Step 3 (where I’m stuck): SAVE THAT EXCEL FILE IN SAID SEPARATE FOLDER INTO A MODEL FILE FIELD. I’d greatly appreciate any help :)