Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement spelling insensitive search in django & ProstgreSQL?
What I wanted to achieve is, if user enters search for "laptp" then database should return results with actual word "Laptop". Similarly if user enters "ambroidery", then database should return results with both "embroidery" and "embroidred" words containing strings. Hope it clears!! So what I tried is, I went through whole django documentation and closest thing I found is "Trigram Similarity" search. I followed documentation and tried this: data = 'silk' data= Product.objects.annotate( similarity=TrigramSimilarity('description', data)).filter(similarity__gt=0.3).order_by('-similarity') In my database, I have Products whose description contains word "silky" but everytime I runs this qury I get empty query set. Even when I put data value "silky", again I got empty query set. So first of all suggest me that whether this is right approach for what I wanted to achieve and secondly if it is, then why it is returning empty query set? -
How to install tensor flow for Django Applications
I am trying to use tensorflow for my django web application. I installed tensor flow in anaconda using the following commands conda create -n tensorflow_env tensorflow conda activate tensorflow_env Now I am trying to impot tensor flow and executing the belwo script in django shell but I am getting an error ModuleNotFoundError: No module named 'tensorflow' I have read similar questions but they talk about the tensorflow environment is different from the conda environment. How do I make sure that the tensorflow imports work in my anaconda environment. I am pretty confused about these environments. Here is my code from django.db.models import Avg,Sum from django.db.models.functions import TruncDate import pandas as pd import tensorflow as tf import matplotlib as mpl import matplotlib.pyplot as plt # Create your views here. from myapp.models import Order orders = Order.objects.all().annotate(date = TruncDate('timestamp')).values('itemName','date').annotate(itemPrice = Avg('itemPrice'),quantity=Sum('quantity'),orderPrice = Sum('orderPrice')) df = pd.DataFrame(list(orders)) -
Passing Trait Value to SubFactory Django
I have two factories. class DispatchDataFactory(factory.django.DjangoModelFactory): class Meta: model = models.DispatchData order = factory.SelfAttribute('order_data.order') sku = factory.LazyAttribute(lambda obj: '%d' % obj.order_data.sku) category = SKUCategory.SINGLE quantity = 50 class Params: combo_sku=False order_data = factory.SubFactory(OrderDataFactory, combo_sku=factory.SelfAttribute('combo_sku')) combo_sku = factory.Trait( sku=factory.LazyAttribute(lambda obj: '%d' % obj.order_data.sku), category=SKUCategory.COMBO, quantity=1 ) class OrderDataFactory(factory.django.DjangoModelFactory): class Meta: model = models.OrderData order = factory.SubFactory(OrderFactory) category = SKUCategory.SINGLE quantity = 75.6 price_per_kg = 10.5 sku = factory.SelfAttribute('crop_data.id') class Params: crop_data = factory.SubFactory(CropFactory) combo_data = factory.SubFactory(ComboSkuFactory) combo_sku = factory.Trait( sku=factory.SelfAttribute('combo_data.id'), category=SKUCategory.COMBO, quantity=1, price_per_kg=34.56 ) so if combo_sku is True then it must on combo_sku in OrderDataFactory. I am getting following error. Cyclic lazy attribute definition for 'combo_sku'; cycle found in ['category', 'combo_sku'] Is there any other way to pass trait value to SubFactory. -
'The view dashboard.views.index didn't return an HttpResponse object. It returned None instead.' when using POST request of specific variable
So I am trying to build a simple view which allows user to change their avatar using form submission. Rendering the view before the POST request works just fine however when a user submits a new image file through form submission I got the following error: Value Error at / The view dashboard.views.index didn't return an HttpResponse object. It returned None instead. The following is a snippet from my view.py @login_required(login_url='/accounts/login/') def index(request): if request.method == 'POST': if 'imagefile' in request.POST: form = forms.AvatarUpdate(request.POST, request.FILES) if form.is_valid(): image = request.FILES['image'] request.user.avatar = image request.user.save() return redirect('/') else: form = forms.AvatarUpdate() return render(request, 'dashboard/index.html', {"this_page": "home", "form": form}) While the forms.py is as follow: class AvatarUpdate(forms.Form): imagefile = forms.ImageField(widget=forms.FileInput(attrs={'name': "imagefile"}), label="Change user avatar") My intention here is that the model would only be saved only if the POST request contains the variable imagefile. How should I go about fixing the problem? -
Django delete in a transaction
In a Django view, if two requests enter an atomic block that gets a model instance (that exists) and deletes it with transaction.atomic(): MyModel.objects.get( id=1234 ).delete() what happens when they exit the block? Would an exception be raised on one of them? If so, what exception? (i.e. so I can catch it) -
Django Simplejwt: Return existing valid token on relogin
I am using djangorestframework-simplejwt for jwt based authentication in my DRF project. But every time i login a new token is getting generated. How can i make sure when a valid token exists for a user then same is returned on relogin. -
React/Material UI - Can I not use <form> tag anymore when creating forms?
I am working on a React/Django project and my form input elements are created using Material UI. In my backend, I am using Django Rest Framework for serializers and APIs. On my frontend, I use material-ui input components but I no longer wrap the input elements within the form tag because I am sending my requests via ajax and in the background I have Django to handle the serialization and validation of the request data. Is this a good approach or should I always wrap input elements inside form tag? What my react code looks is something like: const TestComponent = props => { const [state, setState] = useState({ input1: "" }) const testPost = (data,token) => new Promise((res,rej) => { let endpoint = '/test/add/' let options = { method: "POST", headers: { 'Content-Type': 'application/json', 'Authorization': `Token ${token}` }, body: JSON.stringify(data), credentials: 'include' } fetch(url,options) .then(res=>res.json) .then(data=>{res(data)}) .catch(err=>{rej(err}) }) const handleChange_input1 = e => { setState(prev => ({ ...prev, input1: e.target.value })) } return( <Grid container> <Grid item> <TextField label="Input 1" value={state.input1} onChange={handleChange_input1} /> <Button variant="text" onClick={e => { testPost({input1: state.input1},"token123") }} > Submit </Button> </Grid> </Grid> ) } export default TestComponent -
Get value from Django model
Can I access Django models using this methods ? views.py def participant_view(request): participant = get_object_or_404(Participant, user=request.user) seconds_left = participant.seconds_left model.py class Participant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) seconds_left = models.FloatField(default=0) def __str__(self): return self.user.username if not, what the correct way to do so ? -
Ecommerce checkout: when and where to create intermediate and final order for items in cart in relational database
I am working on a ecommerce project(in Django) where users can place orders. Users can add items they are interested to buy in a shopping cart which is persistent. They go through the checkout process to place the order. I am not clear how to store and manage intermediate order stage before creating final order in order table. I am thinking of these options: using separate cart, order table: cart table will have items selected by the user. when they click checkout, create an order but with a flag which says it is in intermediate stage. when payment is initiated, it will be marked as a final order. using separate table for cart, checkout and order: cart table will have items selected by the user. when they click checkout, create a checkout entry. when payment is initiated, create an entry in the order table. here checkout needs to have replica of the order structure. this seems to duplicate lot functionality using cart+checkout(combined), order table: cart table will have items selected by the user. when they click checkout, checkout stages will be stored in same table. this is similar to the magento sales_flat_quote table. when payment is initiated, a final order … -
Rainfall Intensity Prediction using Machine Learning
I have a project that needs to predict Rainfall Intensity on upcoming days or weeks. I learned that I need to use machine learning but I'm new to this technology. I will explain my project below My project is a rainfall advisory system running on Django, which have a arduino(tipping bucket) connected to it to measure the rainfall's intensity, (e.g. 30mm/hr = heavy, 50mm/hr = torrential) on present time (live graph on chartjs). But I also have records of the data and I think I'm gonna need those for prediction. My question is How am I gonna do this? - Predict the intensity on upcoming days, weeks. (how much mm/hr) - What are the requirements to save my time, I have a deadline, can I complete this within 1 week? (surprise deadline lol) - dependencies, tools. - Display prediction on graph (chartjs) I also found that you need a CSV file for the model to read, how to read the data directly from my database without importing a CSV file? I think better idea for visualization is send prediction data to database and display it to my graph. Any suggestions/tips please? Thanks! -
Django ValueError: The view usermanager.views.group_perm didn't return an HttpResponse object. It returned None instead
I am creating a News Website. When I try to delete permission from a group the same error is showing. The codes above this function are almost same. But they are working fine.Please Help This is my view file def group_perm(request, name): if not request.user.is_authenticated: return redirect('my_login') perm = 0 for i in request.user.groups.all(): if i.name == "masteruser": perm = 1 if perm == 0: error = "Access Denied" return render(request, 'back/error.html',{'error': error}) permission = Permission.objects.all() for group in Group.objects.filter(name=name): gperm = group.permissions.all() return render(request, 'back/group_perm.html', {'gperm':gperm, 'name':name, 'permission': permission}) def group_permission_del(request, gname, name): if not request.user.is_authenticated: return redirect('my_login') perm = 0 #"request.user" means current logged User for i in request.user.groups.all(): if i.name == "masteruser": perm = 1 if perm == 0: error = "Access Denied" return render(request, 'back/error.html',{'error': error}) group = Group.objects.get(name=gname) gperm = Permission.objects.get(codename=name) group.permissions.remove(gperm) return redirect('manage_permission') -
How to submit a form to server using ajax?
I'm trying to send a button id to my server using ajax to submit a form because I don't want to load a new page everytime I click on a button. But it isn't working and I don't know why. It donesn't even change the button thexto 'x' anymore. I'm very new to ajax btw Here is my script: <script> var docFrag = document.createDocumentFragment(); for (var i=0; i < 3 ; i++){ var row = document.createElement("tr") for (var j=0; j < 3 ; j++){ var elem = document.createElement('BUTTON'); elem.type = 'button'; elem.id = 'r'+i+'s'+j; elem.value = 'r'+i+'s'+j; elem.onclick = function () { document.getElementById("klik").value = this.id; document.getElementById("ID").value = this.id; //document.getElementById("klik").submit(); $("#klik").submit(function(event){ event.preventDefault(); //prevent default action var post_url = $(this).attr("action"); //get form action url var request_method = $(this).attr("method"); //get form GET/POST method var form_data = new FormData(this); //Creates new FormData object $.ajax({ url : post_url, type: request_method, data : form_data, contentType: false, cache: false, processData:false }).done(function(response){ alert('Done'); }); }); var id = this.getAttribute('id'); var novi = document.createElement('BUTTON'); novi.type = 'button'; //alert("This object's ID attribute is set to \"" + id + "\".") novi.value = id; novi.innerHTML = 'x'; this.parentElement.replaceChild(novi,this); }; elem.innerHTML = elem.value; docFrag.appendChild(elem); } document.body.appendChild(docFrag); document.body.appendChild(row); } </script> -
Why EmailMessage.attach_file(file_path, type) attaches blank document in the mail, but the attachment shows a size?
I am using EmailMessage to send email. And need to attach a pdf. My code is below: msg = EmailMessage(email_subject, html_content, from_email, [email], reply_to=reply_to, attachments=attachment_list) msg.encoding = "utf-8" msg.attach_file('alert_pdf_files/846d5c04___alert_89072e99.pdf', mimetype="application/pdf") msg.content_subtype = "html" msg.send() In the mail, i find the attachment and it shows a convincing size too. But when i open it or download it, it looks blank. The SS is attached. Please help me fix this. It would be appreciated. -
Django messages: how can i change message text in html?
View: messages.add_message(request, messages.ERROR, 'Cells marked incorrectly.') HTML: {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}"> {{ message }} </li> {% endfor %} </ul> {% endif %} Problem: I need to remove marker which you can see on the related picture. I read so many documentation and forums and find nothing. Maby somebody faces this problem and can help me. -
It Is possible to use own django admin
hi i am new to Django and i want use my own admin site instead of default Django admin site due to my site requirement, Django admin is very power full but i want my own so i can program thing my way, it is very irritating find and use the admin objects even for small change, for that need research and it is time consuming task. please help me https://docs.djangoproject.com/en/3.0/ref/contrib/admin/ -
Django - "You may also like" queries
I'm writing on a Forum Software for a while now and I was asking myself as this is also my first Django app how to accomplish a fancy solution to display similar posts items the user maybe also like to see. At least I don't understand how to put all this together on the one side I need the actual post the user is currently viewing, second I might need a somekind of history for previously viewed posts by the user and third I might need tags I can to query for. Does somebody maybe has a good example for me? Thanks in advance -
Django: 'NoneType' object has no attribute 'strftime' error on assigning DateField to a variable in a model class method
I have a Blog model method that create a unique serial number based on the blog's submission_date, submission_time, and id of the blog instance. The Blog model: class Blog(models.Model): title = models.CharField(max_length = 50, blank=False) body = models.TextField() slug = models.SlugField(max_length=50, blank=True) serial_no = models.CharField(max_length=15, blank=True) submit_date = models.DateField(auto_now=True, auto_now_add=False) submit_time = models.TimeField(auto_now=True, auto_now_add=False) ... In the method, I'm taking the date and time fields and converting them to strings through strftime(), then concatenating them. This is the method: def get_serial_no(self): s_date = self.submit_date s_time = self.submit_time str_date = s_date.strftime('%Y%m%d') str_time = s_time.strftime('%H%m') serial = self.id + str_date + str_time return serial I am overriding the save() method to populate slug and serial_no field. The error is only occurring when I'm saving an article. It's pointing to this line: str_date = s_date.strftime('%Y%m%d'); with the error: 'NoneType' object has no attribute 'strftime'. As far as I understand I am properly referencing to the Date type. Therefore, it should call its strftime() function. What am I doing wrong? -
How can I solve this problem of connecting MySQL with Django
enter image description here This is the issue from running the server -
value too long for type character Django Factory
I have below OrderDataFactory class. class OrderDataFactory(factory.django.DjangoModelFactory): class Meta: model = models.OrderData order = factory.SubFactory(OrderFactory) category = 'single', quantity = 75.6 price_per_kg = 10.5 sku = factory.SelfAttribute('crop_data.id') class Params: crop_data = factory.SubFactory(CropFactory) models.py class OrderData(models.Model): CATEGORY_CHOICES = ( (SKUCategory.SINGLE, 'Single Sku'), (SKUCategory.COMBO, 'Combo Sku'), ) sku = models.PositiveIntegerField(null=False, validators=[MinValueValidator(1)]) order = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.FloatField() price_per_kg = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=8) class Meta: unique_together = (('sku', 'order', 'category'),) Category.py class SKUCategory: SINGLE = 'single' COMBO = 'combo' i am getting following error. django.db.utils.DataError: value too long for type character varying(8) even max length for category is 6. -
Explain about the function at end of the code. It is in Django choices field. Explain what that function do in Django
Explain about the function at end of the code. It is in Django choices field. Explain what that function do in Django. from django.db import model class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMEN def is_upperclass(self): return self.year_in_school in (self.JUNIOR, self.SENIOR) -
Django admin not responding on host site
I am working on Django admin creation using "python manage.py createsuperuser" in the shell.I created username,email and password and then ran the server using "python manage.py runserver" in the terminal of PyCharm. What I got is: (venv) H:\django project\mysite1>python manage.py createsuperuser Username (leave blank to use 'maitreya'): mtr007 Email address: maitreya@gmail.com Password: Password (again): Superuser created successfully. AND AFTER THIS I RAN THE SERVER (venv) H:\django project\mysite1>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 26, 2020 - 11:32:06 Django version 3.0.5, using settings 'mysite1.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [26/Apr/2020 11:32:08] "GET / HTTP/1.1" 404 2028 [26/Apr/2020 11:32:13] "GET /admin/ HTTP/1.1" 302 0 [26/Apr/2020 11:32:13] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [26/Apr/2020 11:32:27] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 Now What happens is that the web page has created a Django administration login and accepting my username and password but suddenly the site stops working. I am posting a screenshot of the site. Can someone address and solve what should I do(should install some module or verify the path etc.) or look for new versions of some django documentations. -
ValueError: source code string cannot contain null bytes in Django
Right now, I am learning django framework and I got stuck on the following problem Here is the error message Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x044BF148> Traceback (most recent call last): File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\management\base.py", line 376, in check all_issues = self._run_checks( File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\web_projects\pages\pages_project\urls.py", line 21, in <module> path('', include('pages.urls')), File "C:\Users\nodvo\.virtualenvs\web-e0x1-Fid\lib\site-packages\django\urls\conf.py", line … -
Delete operation using Serializes
In official document serializers class show only create & update method only. There is any way to perform delete method? is say Yes how? if say No why? -
Bad request(400) for POST request on django rest-framework api via jquery [duplicate]
I am quite new to django and jquery. I am trying to perform a post request on: my model class part_list(models.Model): designID = models.ForeignKey('modules', on_delete=models.CASCADE) PartID = models.ForeignKey('parts',on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return "DesignID :{}, PartID :{}".format(self.designID,self.PartID) class Meta: unique_together = (('designID','PartID')) my serializer class sub_part_list_serializer(serializers.ModelSerializer): class Meta: model = part_list fields = ('designID', 'PartID', 'quantity') my view class sub_part(generics.ListCreateAPIView): serializer_class = sub_part_list_serializer def get_queryset(self): queryset = part_list.objects.all() designID = self.request.query_params.get('designID',None) print(self.request) if designID is not None: queryset = queryset.filter(designID__exact=designID) return queryset and my jquery $('#test').on('click', function(){ var data1 = {}; data1["designID"] = "bar-123"; data1["PartID"] = "A102"; data1["quantity"] = 3; console.log(data1); $.ajax({ type: "POST", url: "bon/sub_part/", data: data1, contentType: "application/json; charset=utf-8", success: function(data){ alert(data); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("some error " + String(errorThrown) + String(textStatus) + String(XMLHttpRequest.responseText)); } }); the error it is showing is Bad Requesterror{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} when I am making post requests directly from the API it is working fine. I am not using any user authentication. I also tried to add the csrf token in the request header but nothing changed Please Help! -
Is there anyway to pass more than 2 arguments in Django's template url function?
I want to pass 3 arguments to this path: path('assignment/<str:class_id>/<str:assignment_id>/<str:edit>', views.assignment, name='teacher-assignment') Here is the template code: <a href="{% url 'teacher-assignment' class_id=class_id assignment_id=assignment.id|uuid_to_str edit='edit=false' %}">{{ assignment.assignment_name }}</a> However, Django throws a no reverse match found error showing only 2 of these arguments listed in the passed arguments. The template url function's comments also show only 2 arguments being passed. How would I pass 3 arguments to the URL dispatcher?