Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Datetime function
Am aiming for the value 'grade' to be incremented by 1 on 25th every month. The below function doesn't seem to be working. Where could I be going wrong? Attached is the model and function. class Student(models.Model): student_name = models.CharField(max_length=100, null=True) extra_role = models.CharField(max_length=100, default='None', null=True) gender = models.CharField(max_length=20, choices = gender, default = "female") dob = models.DateField(null=True, blank=True) grade = models.IntegerField(choices=grade) parent_phone = PhoneField(blank=True, help_text='Contact phone number') # admNo = models.AutoField() @property def age(self): if(self.dob != None): age = date.today().year - self.dob.year return age @property def sgrade(self): if datetime.today().day == 25: grade = self.grade +1 return grade -
How to solve add key and value in local storage in the django website?
This is a Social network website. It's build in python django.I need to add the user login section the values stored in the local storage section. in this website have 2 login method one is end user and another is companies the main setting is need user is login that time the key and value is need to store the local storage this is need for cross site login for users for example facebook users have join in through instagram. please help me for the solution ? I need to fix the set cookies in the session also -
Create an API Gateway on an existing python project
To explain the context, I am currently developing a microservice application with 4 entities: Publishers [with a simulator]. A Queue system Receivers (which also do local processing) [in Python]. A front end that GETs data with a REST API on the receiver [in React]. My problem is the following: To set up a Gateway API between the receiver and the front end, I simply threaded the Receiver microservice to add a classic Flask execution. It seems to work, but I'm sure it's not the best solution... Initially I really thought of the Gateway API as a microservice in its own right, rather than an "add-on" to the Receiver -
model_to_dict: AttributeError: 'str' object has no attribute '_meta'
I have following error when I run the code. Can any of you please help to me solve the issue ? AttributeError: 'str' object has no attribute '_meta' Traceback (most recent call last): File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\ipcramk\Desktop\Desktop files\pYTHON TRAINING\Django\Quality_Check_UI\QC_project\app1\views.py", line 328, in qc3_approval_view cn_data_form = qc3_approval_form( instance=request.GET['key'] ) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\forms\models.py", line 292, in __init__ object_data = model_to_dict(instance, opts.fields, opts.exclude) File "C:\Users\ipcramk\PycharmProjects\Quality_Check_UI\lib\site-packages\django\forms\models.py", line 82, in model_to_dict opts = instance._meta AttributeError: 'str' object has no attribute '_meta' [24/Oct/2021 12:02:40] "GET /cn_entry/approval_page?key=2 HTTP/1.1" 500 92849 Views.py def qc3_approval_view(request): cn_data_form = qc3_approval_form( instance=request.GET['key'] ) forms.py class qc3_approval_form(forms.ModelForm ): class Meta: model = cn_data_tables fields = ('status_qc3',) models.py class cn_data_tables(models.Model): sl_no = models.AutoField(primary_key=True) cn_number = models.CharField(max_length=10, null=False) status_qc3 = models.ForeignKey( 'status_list_table',related_name='status_qc3', on_delete=models.CASCADE, default=3 ) def __int__(self): return self.sl_no -
Json Response is not returning through success (Showing direct response after submit)
I am building a Blog App and I am trying to save instance through ajax and I am returning Json Response in view, But Json Response is not successfully returning instead it is showing response after form submit like {"action": "saved"}, I have tried by changing response but it is showing exactly the returnable response, It is supposed to show success message but it is not returning that. Form is submitting fine in Admin. views.py def posts(request): posts = Blog.objects.all() if request.method == "POST": form = BlogForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.submit_by = request.user new_post.comment_of = comment new_post.save() else: form = BlogForm context = {'posts':posts,'form':form} return render(request, 'posts.html', context) def EditAllPosts(request, blog_id): comment = get_object_or_404(Blog, pk=blog_id) if request.method == "POST": form = BlogForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.submit_by = request.user new_post.comment_of = comment new_post.save() return JsonResponse({'bool': True}) else: return JsonResponse({'bool': form.errors}) posts.html {% for blog in posts %} <form method="post" id="blog-form-" data-data="{{coms.pk}}" enctype="multipart/form-data" action="{% url 'EditAllPosts' blog.id %}"> {% csrf_token %} {{form}} <input type="submit" data-data="{{coms.pk}}" onclick="saveInstancOnClick({{forloop.counter}})"> </form> <script> $(document).ready(function(){ function saveInstancOnClick(id) { document.getElementById(`blog-form-${forloop.counter}`); var _questionid=$(this).data('data'); let thisElement = $(this); $.ajax({ url: thisElement.attr('action'), type:"post", data:{ csrfmiddlewaretoken:"{{csrf_token}}" }, dataType:'json', success: function(res) { if (res.bool == true) { alert("Worked") } } … -
Replacing a letter with "#" and reverse. In Python Django and HTML
I am new to python and doing a test program that replaces all the letters in a given text with signs. def encrypted(request): text = request.GET['text'] text = text.replace("a", "#.") text = text.replace("b", "##.") text = text.replace("c", "###.") text = text.replace("d", "####.") text = text.replace("e", "#####.") text = text.replace("f", "######.") etc... return render(request, 'encrypted.html', {'text': text}) I have achieved that but I have tried reversing it the same way and it does not work. def decrypted(request): ftext = request.GET['text'] ftext = ftext.replace("#.", "a") ftext = ftext.replace("##.", "b") ftext = ftext.replace("###.", "c") ftext = ftext.replace("####.", "d") ftext = ftext.replace("#####.", "e") etc... return render(request, 'decrypted.html') So the text does not appear at all on the page. <html lang="en"> <head> <meta charset="UTF-8"> <title>yCrypt</title> </head> <body> TEXT DECRYPTION: {{ftext}} </body> </html> I wonder why it shows no code issues whatsoever. Maybe there is a simplier way to make this possible? -
Django signals doesnt receive any signals (doesnt work)
Here is my code : models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils import timezone GENDER = ( ("MALE", "Male"), ("FEMALE", "Female"), ) class UserManager(BaseUserManager): def create_user(self, email, username, password=None, is_active=True, is_staff=False, is_superuser=False): # , **extra_fields if not email: raise ValueError('Users must have email address') if not username: raise ValueError('Users must have username') if not password: raise ValueError('Users must have password') # Normalize example: Test@gmail.com ---> test@gmail.com email = self.normalize_email(email) user = self.model(email=email, username=username, date_joined=timezone.now()) # , **extra_fields user.is_staff = is_staff user.is_superuser = is_superuser user.set_password(password) user.save() return user # Called when we run python manage.py createsuperuser def create_superuser(self, username, email, password=None): user = self.create_user(email, username, password, is_staff=True, is_superuser=True) return user # Abstract Base User will give three fields by default (id, password, last_login) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True, blank=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) objects = UserManager() # USERNAME_FIELD and password are required to login USERNAME_FIELD = 'email' # REQUIRED_FIELD is a list of the field names that will be prompted # for when creating a user via the createsuperuser management command REQUIRED_FIELDS = ['username'] def __str__(self): return self.email class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) … -
How to get the difference in seconds between two datetime fields in Django template?
Minutes is the smallest unit used in Django tags timesince and timeuntil, not sure how to get the difference in seconds between two datetime fields. For example, it is 11 seconds between 2021-10-24 15:11:22 and 2021-10-24 15:11:33. -
Django no such table
In the development environment of a new Django project I have 2 apps and I am was running into issues of "no column named" exceptions. I ended up deleting the sqlite db and retried python manage.py makemigrations and pyhon manage.py migrate now I run into a new exception of no table exits. I can verify from the sqlite model that the table do not exits, but I did not receive any errors after deleting the database and rerun python manage.py makemigrations and python manage.py migrate In models.py for my products app from django.db import models from django.db.models.fields import CharField from instructions.models import Instruction # Create your models here. class Product(models.Model): productName = models.CharField(max_length=200) productDescription = models.TextField(blank=True) productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) productSubQuantity = models.IntegerField(default=1, blank=False) productAvailable = models.BooleanField(default = True) productCreated_at = models.DateTimeField(auto_now_add = True) productUpdated_at = models.DateTimeField(auto_now = True) productSlug = models.SlugField(max_length = 255, unique = True, help_text = "Unique text for url created from product name") productMetaKeywords = models.CharField("Meta keywords for SEO", max_length = 255, help_text ="Comma delimited words for SEO") productMetaDescription = models.CharField("Meta description", max_length = 255, help_text="Content for meta tag description") instruction = models.ForeignKey(Instruction, on_delete = models.CASCADE, related_name = "instruction") class Meta: db_table = 'products' ordering … -
New Django, SQL user here: How do I reference my database objects in code in Django?
I know there are tons of resources online to figure this out, but I feel like the situation with my models is very weird, and I know the syntax can get very messy, so I'm just not sure what to do. So I am creating software for an ice cream company to track their inventory. My models look like this: class sizeCounts (models.Model): class Meta: verbose_name = "Size Count" verbose_name_plural = "Size Counts" #Just to label a collection of sizes with the corresponding flavor so it's not confusing! item_Flavor_Choices = [('CHOCOLATE','chocolate'),('VANILLA', 'vanilla'),('COOKIESNCREME', 'cookiesncreme'), ('STRAWBERRY', 'strawberry')] item_Flavor = models.CharField(max_length=100, choices = item_Flavor_Choices, default='chocolate') half_Pint_Count = models.IntegerField(default=30) one_Quart_Count = models.IntegerField(default=30) pint_Count = models.IntegerField(default=30) half_Gallon_Count = models.IntegerField(default=30) gallon_Count = models.IntegerField(default=30) def __str__(self): return 'Half Pint: %s, Quart: %s, Pint: %s, Half Gallon: %s, Gallon: %s' % (self.half_Pint_Count, self.one_Quart_Count, self.pint_Count, self.half_Gallon_Count, self.gallon_Count) class item (models.Model): class Meta: verbose_name = "Item" verbose_name_plural = "Items" item_Flavor_Choices = [('CHOCOLATE','chocolate'),('VANILLA', 'vanilla'),('COOKIESNCREME', 'cookiesncreme'), ('STRAWBERRY', 'strawberry')] item_Flavor = models.CharField(max_length=100, choices = item_Flavor_Choices) size_Counts = models.ForeignKey(sizeCounts, on_delete=models.CASCADE, default = None) def __str__(self): return self.item_Flavor As you can see, I have an item model and a sizeCounts model. An item has a flavor and a set amount of quantity for each size … -
I'm trying to use django channels but it keeps throwing error
im trying to implement django channels app in my django project.but whenever I put channels app in my django settings.py installed app it throws an error as bellow Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "E:\sunil_sachin\SSMOS_env\lib\site-packages\django\apps\config.py", line 124, in create mod = import_module(mod_path) File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "E:\sunil_sachin\SSMOS_env\lib\site-packages\channels\apps.py", line 4, in <module> import daphne.server File "E:\sunil_sachin\SSMOS_env\lib\site-packages\daphne\server.py", line 5, in <module> from twisted.internet import asyncioreactor # isort:skip File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\internet\asyncioreactor.py", line 16, in <module> from twisted.logger import Logger File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\logger\__init__.py", line 105, in <module> from ._logger import Logger, _loggerFor File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\logger\_logger.py", line 269, in <module> _log = Logger() File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\logger\_logger.py", line 65, in __init__ from ._global import globalLogPublisher File "E:\sunil_sachin\SSMOS_env\lib\site-packages\twisted\logger\_global.py", line 17, in <module> from ._buffer import … -
How to retain a queue of model instances in django to be used accross views (please read description)
I am trying to implement an algorithm as a variation of priority based sorting algorithms used in operating systems. Suppose i have a model Task: class Task(models.Model): priority = 1 name = "task" burst_time = 5 arrival_time = models.DateTimeField(auto_now_add=True) Something like this. And one of my view does something to the task: def my_view(request, pr): instances_queue = Task.objects.filter(priority=pk).order_by(-arrival_time) instance = instance_queue[1] #do something with the instance instance.burst_time = instance.burst_time - 1 instance.save() #if burst_time == 0 dequeue But simply using objects.filter() is not good, so what i ideally need is, to create a class like i have here: class Queue(): def __init__(self, quantum, priority): self.items = [] self.quantum = quantum self.priority = priority def isEmpty(self): return self.items == [] def enqueue(self, item): item.Qtime = self.quantum item.priority = self.priority self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def peek(self): return self.items[-1] as a model, where items are instances of my Task model. I should be able to make multiple queues and interchange tasks based on needs. The way i am implementing this is getting far too complex. Can someone please help with the design of the Queue model so i can use that as a universal queue for my Task … -
Unable to retrieve individual blog in react using axios
I have spent a couple of time trying to figure out why I'm not able to obtain individual blog post detail page using axios. The code does not return any data (It is returning undefined) I have the follow code: import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import axios from 'axios'; export default const blog_detail = (props) => { const [blog, setBlog] = useState({}); useEffect(() => { const slug = props.match.params.id; const fetchData = async () => { try { const res = await axios.get(`https://example.com/blog/${slug}`); setBlog(res.data); } catch (err) { } }; fetchData(); }, [props.match.params.id]); const createBlog = () => { return {__html: blog.body} }; const capitalizeFirstLetter = (word) => { if (word) return word.charAt(0).toUpperCase() + word.slice(1); return ''; }; return ( <div> <div dangerouslySetInnerHTML={createBlog()} /> </div> ); }; The code returns data for those I practice with but never works in my case but everything seems to be similar to theirs. -
How do I fix internal server error while executing JQuery?
I was building a quiz app via python and Django.I wrote some jQuery code and it supposed to show result in console.My code is attached below.It shows "Internal Server error" It is written inside quiz.js console.log("Hello") const url=window.location.href console.log(url) const quizBox=document.getElementById('quiz-box') let data $.ajax({ type:'GET', url:`${url}data`, success:function (response){ console.log(response) data=response.data data.forEach(el=>{ for(const [question,answers] of Object.entries(el)){ quizBox.innerHTML+=` <hr> <div class="mb-2"> <b>${question}</b> </div> ` } }) }, error:function (error){ console.log(error) } }) -
Django how to send array to JavaScript for dynamically display pie chart?
I have an array in Django views.py and I want to send it to HTML and display a piechart, but failed, I've tried many other methods and read many tutorials, in most of the case, they have a field in models that store some number, and they display those number. In my case, I need to calculate the subtotal of tasks that are in different states. I'm not sure how to output those data to chart.js with proper labels or any other piechart if there's any recommendation? views.py def visualisation(request, project_id): project = Project.objects.get(id=project_id) counts_data = Todo.objects.aggregate( to_do_count=Count('id', filter=Q(status='to_do')), in_progress_count=Count('id', filter=Q(status='in_progress')), done_count=Count('id', filter=Q(status='done')) ) return render(request, 'todo_lists/progress.html', {"counts_data": counts_data}) html <script> $(document).ready(function() { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'doughnut', data: { labels: [1,2,3], datasets: [{ label: '# of Votes', data:counts_data, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)' ], borderWidth: 1 }] }, options: { responsive:false } }); }); </script> -
DRF & drf-haystack: How to use prefetched querysets in drf-haystack's serializer
Is there any way to use a prefetched queryset when retrieving information associated with an object in a HaystackSerializer's SerializerMethodField? In a normal DRF view, it is possible to pass prefetched queries to the serializer using prefetch_related or annotate from its own queryset instead of the Search queryset. What should I do in this case? # search_indexes.py class VideoIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr="title") published_at = indexes.DateTimeField(model_attr="published_at") def get_model(self): return Video # views.py class VideoSearchView(ListModelMixin, HaystackGenericAPIView): index_models = [Video] serializer_class = VideoSearchSerializer filter_backends = [HaystackFilter, HaystackOrderingFilter] ordering_fields = ["published_at"] def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) # serializers.py class VideoSearchSerializer(HaystackSerializer): is_viewed = serializers.SerializerMethodField() is_favorited = serializers.SerializerMethodField() class Meta: index_classes = [VideoIndex] search_fields = ("text",) fields = ( "title", "is_viewed", "is_favorited", "is_wl", ) def get_is_viewed(self, obj): user = self.context["request"].user if user.is_authenticated: try: History.objects.get(user=user, video_id=obj.pk) return True except History.DoesNotExist: pass return False def get_is_favorited(self, obj): user = self.context["request"].user if user.is_authenticated: try: Favorite.objects.get(user=user, video_id=obj.pk) return True except Favorite.DoesNotExist: pass return False -
Converting Form Function to a Class Based View in a Django Project
I am trying to convert my Form which is laid out in a function to be in a class based view: Here is what I have reach out. Function: def add_business_plan(request): info = Info.objects.all() if request.method == 'POST': form = infoForm(request.POST) if form.is_valid(): form.save() business_name = form.cleaned_data.get('businessName') info_id = form.instance.id messages.success(request, f'PDF created for {business_name}!, No.({info_id})') return render(request, 'businessplan/businessplan.html', {'form': form, 'successful_submit': True}) else: form = infoForm() print(form.errors) return render(request, 'businessplan/businessplan.html', { 'form': form, 'successful_submit': False, "Info": info } ) -
Django ValueError The view todo_lists.views.visualisation didn't return an HttpResponse object. It returned None instead
everyone. I have views.py here, I want to calculate different status' tasks and output to chart.js piechart. I have tried many ways but none of them works. I have an error saying my views def didn't return HttpResponse, can anyone tell me what it is, please? I used template tags in html. Thanks. views.py ''' def visualisation(request, project_id): project = Project.objects.get(id=project_id) counts_data = Todo.objects.annotate( to_do_count = Count('id', filter=Q(status='to_do')), in_progress_count = Count('id', filter=Q(status='in_progress')), done_count = Count('id', filter=Q(status='done')) ).order_by('-to_do_count') context = {'counts_data', counts_data} return render(request, 'todo_lists/progress.html', context) ''' html ''' data: { labels: [1,2,3], datasets: [{ label: '# of Votes', data:[{% for todo in counts_data %} {{ todo }}, {% endfor %}],, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)' ], borderWidth: 1 }] }, ''' -
How to troubleshoot a failing Django LDAP connection
I am using Django Rest with active directory authentication. I have built a simple app with the following settings: import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType # Baseline configuration. AUTH_LDAP_SERVER_URI = 'ldap://ad_server.com' AUTH_LDAP_BIND_DN = "CN=binduser,OU=Users,OU=ad_server,DC=ad_server,DC=com" AUTH_LDAP_BIND_PASSWORD = "somepassword" # Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "OU=Groups,OU=ad_server,DC=ad_server,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") # Simple group restrictions AUTH_LDAP_REQUIRE_GROUP = "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com" AUTH_LDAP_DENY_GROUP = "cn=disabled,ou=django,ou=groups,dc=example,dc=com" # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", 'username': 'cn', "email": "mail", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com", "is_staff": "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com", "is_superuser": "CN=prod,OU=Groups,OU=ad_server,DC=ad_server,DC=com", } # This is the default, but I like to be explicit. AUTH_LDAP_ALWAYS_UPDATE_USER = True # Use LDAP group membership to calculate group permissions. AUTH_LDAP_FIND_GROUP_PERMS = True # Cache distinguished names and group memberships for an hour to minimize # LDAP traffic. AUTH_LDAP_CACHE_TIMEOUT = 3600 # Keep ModelBackend around for per-user permissions and maybe a local # superuser. AUTHENTICATION_BACKENDS = ( "django_auth_ldap.backend.LDAPBackend", "django.contrib.auth.backends.ModelBackend", ) Running an LDAP search from the cli works just fine However when I try to authenticate with the http://localhost:8000/admin/ I get the following error. The terminal on the other hand doesn't show anything: There must be a better way to troubleshoot … -
How can I create a database using django then connect that database to my django app?
I am making an app that makes sql queries and display the resulting tables, I have already a database connected to my app and makes the queries correctly but I want to upload a sql file, create the database in my computer and then make queries to that database. Is that possible? Can django create a database from a sql file in mysql server and then use that database? Or do I need to make everything manual like create the database and then change my settings.py? -
Django 3.2.8 custom middleware returns 302 redirect errors
I am looking to use custom middleware to redirect a user to a their profile role if their profile role value is set to '0'. Below is the current code I am using, but is causes a 302 redirect loop. This is based on other examples I found on the internet, but no luck in finding a fix. Any ideas will be greatly valued. from django.shortcuts import redirect from django.utils.deprecation import MiddlewareMixin from django.http import HttpResponseRedirect class UserRoleMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def process_request(self, request): redirect_url = '/role/' if request.user.is_authenticated and request.user.profile.role == '0': print('user must define a role') return HttpResponseRedirect(redirect_url) return None Response: [23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0 user must define a role [23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0 user must define a role [23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0 user must define a role [23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0 -
How to make a correct redirection in django app after user delete his message in website?
i am developing a website watching a video course and sometimes i don't agree with mentor decisions about solving some tasks. And while i am trying to figure this out, the problem has already taken really much time and i haven't still found how to solve this. At first i show the necessary source code. urls.py and the the error url: path('delete-message/<str:pk>/', views.delete_message, name='delete-message') views.py and function where error happens: @login_required def delete_message(request, pk): message = Message.objects.get(id=pk) room_id = message.room.id if request.method == 'POST': message.delete() return redirect(f'room/{room_id}') ### WHAT DO I HAVE TO DO ??? return render(request, 'delete-message.html') delete-message.html and error form: <form method="POST"> {% csrf_token %} <h2> <p>Are you sure you want to delete this message ?</p> </h2> <a href="{{request.META.HTTP_REFERER}}">Go Back</a> <input type="submit" value="Confirm"> </form> After redirect() works it sends me to the unexisted url: 127.0.0.1:8000/delete-message/10/room/5but it had to be http://127.0.0.1:8000/room/5... Why is it not as such result as i've expected ? Also i've tried to do this: In the views.py i change function where except of redirect i transfer room_id to the template: @login_required def delete_message(request, pk): message = Message.objects.get(id=pk) room_id = message.room.id if request.method == 'POST': message.delete() return render(request, 'delete-message.html', {'id': room_id}) In the template delete-message.html i … -
Aggregate and condense time-series values using Django Querysets?
I'm currently trying to create a small crypto tracker for fun using CoinMarketCap's API. The API can be called every 5 minutes – each time returning the current exchange value, however I want to plot my graph in 30-minute intervals. How can I condense my exchange value information of 5-minute increments down to 30-minute data points featuring the respective "Open, High, Low, Close" information? (aka first exchange value, max exchange value, min exchange value, last exchange value) Example data: 2021-10-23 10:00:00 – price: 50 2021-10-23 10:05:00 – price: 45 2021-10-23 10:10:00 – price: 43 2021-10-23 10:15:00 – price: 47 2021-10-23 10:20:00 – price: 51 2021-10-23 10:25:00 – price: 70 2021-10-23 10:30:00 – price: 65 2021-10-23 10:35:00 – price: 55 2021-10-23 10:40:00 – price: 47 2021-10-23 10:45:00 – price: 51 2021-10-23 10:50:00 – price: 62 2021-10-23 11:55:00 – price: 50 Desired output: 2021-10-23 10:00 – open: 50, high: 70, low: 45, close: 57 2021-10-23 10:30 – open: 65, high: 62, low: 47, close: 50 Sample model: class Crypto(models.Model): ticker = models.CharField(max_length=10) price = models.DecimalField(max_digits=7, decimal_places=2) percent_change = models.DecimalField(max_digits=5, decimal_places=2) timestamp = models.DateTimeField(auto_add_now=True) -
Ckeditor how to change button text
My django site uses the image upload feature. I want to change the send it to the server button text to upload I have checked what seems like every source file but I cannot filed a reference to button. How would I go about changing it. I found this posts trying to do the same thing but it is very old -
Use params or class method for on_delete.SET()? (How to change ForeignKey field on delete)
Is it possible to use SET() for a ForeignKey's on_delete with params and/or a class method? I essentially want to leverage the model or the ForeignKey model to generate a new field. E.g. def create_new_relationship(obj): return obj.relationships.first() class Item(models.Model): name = CharField() relationships = ManyToMany("self", on_delete=SET_NULL) relationship = ForeignKey("self", on_delete=SET( # method with params or # class method possible here? )) def create_new_relationship(self): return self.relationships.first() The only other option I can think of is to add a pre/post-delete signal to Item.