Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Identical string in database is why now allowed
I'm currently working in Django and just reminded that professor said don't use same string in different models in same database because it may cause some problems. He said if you want to use it, make another model and use foreign key. But what's the reason we do not have to use identical string in one database? I implemented in two ways, one use another model with foreign key, and one just use same database using same string(but that field is not pk ofc). And it doesn't matter on both cases. So I tried to find why professor said like that, but couldn't find a reason. Is there anyone who can tell me the reason why I shouldn't use identical string in different object in same model? -
Deleting foreign key value
I have got a model that looks like that: coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) When I am trying to delete the coupon using this function: def remove_coupon(request): coupon = Order.objects.get( user=request.user, ordered=False) coupon.coupon.delete() return redirect("core:checkout") It deletes the coupon from Order model, but it also deletes the coupon in the Coupon model. I wanted to make it so it only deletes the value from Order and not from Coupon model. I have also tried on_delete=models.CASCADE , but my site crashes then. Where is the problem? -
how to copy rows from one table to other in django which meet a particular condition?
I want to copy all those fields which meet this condition '''Table1.objects.filter(post_home=True)''' ( where post_home is a boolean field in my Table1)to my other table Table2 which have the same fields as Table1 -
How to change title for the tab of User Add Page of Django admin?
I'm working on Django and wanted to change the default title for the tab of User Add Page of Django admin as marked in the pic : and my admin.py file is : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So what should be done to change it?? Thanks in advance!! -
How to use Enum in a model field as an argument type for a query or mutation in graphene django?
One of the model fields is choice eg. personType = (('Student','Student'),('Teacher','Teacher')) person_type = models.CharField(max_length=20, choices=personType) How can I use the same personType as an argument for a mutation? -
The correct way to use super(type, obj).save() with Django models
In the following code snippet, I have two models (MyObject and MyOption). class MyOption(object): obj = models.ForeignKey( MyObject, on_delete=models.CASCADE, related_name="options" ) defaultoptions = [{}, {}, ...] MyOption.save() is defined as such: def save(self, *args, **kwargs): isvalidated = self.validated() if isvalidated: super(self.__class__, self).save(*args, **kwargs) else: return None # Every object must have at least one corresponding MyOption # Create the default options if none are currently defined if not self.options.all(): for item in defaultoptions: option = MyOption() option.obj = self [setattr(option, k, item[k]) for k in item] option.save() self.save() I get the following error occasionally when I call .save() TypeError: super(type, obj): obj must be an instance or subtype of type How should I edit save() to be solid and error-proof?