Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React axios request to Django backend is empty
So I am trying to send a set of scans (dcm files) to my Django server from my React App. The request should be as follows [ { "scans": [ {"scan_image": <dcm file data>}, {"scan_image": <dcm file data>} ], "name": "Set Name." }, { "scans": [ {"scan_image": <dcm file data>}, {"scan_image": <dcm file data>} ], "name": "Set Name." } ] As shown the request payload is an array of objects. The objects are composed of two attributes, "scans" and "name" where scans attribute is an array of objects containing the data from dcm files. I read the data via the readAsDataURL method of the FileReader object instantiated as I iterate over the files selected by the user to upload. Here is a log of the data gathered in the object needed to be send to the server. Log of the request containing the files to be uploaded to the server Here is a snippet of the axios request upon finishing the request object generation axios({ url: 'http://127.0.0.1:8000/create_sets/', data: requestObject, method: 'post', headers: { "Content-Type": "application/json" } }) .then(res => console.log("Success") ) .catch(res => console.log(res) ) Upon running that script, unfortunately the request payload looks like this [ { "name":"5-AX T1-28522", … -
Django /accounts reset page personalization
In my django project i have my default page for reset password option: i need to: Modify 'Django Administration' header with my own Remove the 'Home > Password reset' menu I try with this code in admin.py for the first point: admin.site.site_title = 'Aida Admin' admin.site.site_header = 'Aida admin console' admin.site.index_title = 'SETTINGS ADMIN ADMINISTRATION' but don't seems to work Someone have an idea? So many thanks in advance -
What oauth library should I use for one-legged authorization
I am trying to create a Django application for one-legged authorization and using python 3.7. I am confused as to which library should I use for the same. Also the documentation is sparse and I am unable to figure if oauthlib is the correct module for the same. Note : I have to use oauth1 not oauth2. -
Django 3 OperationalError: no such table 'web_user'
I want to have 2 types of users in my Django app, so I followed this tutorial and ran python manage.py makemigrations web python manage.py migrate ('web' is the name of my app) Now I want to access the admin part of the site, automatically added by django at localhost:PORT/admin. When I try to access that page, this error shows: django.db.utils.OperationalError: no such table: web_user Here's my models.py: from django.contrib.auth.models import AbstractUser from django.db import models from web import constants class User(AbstractUser): USER_TYPE_CHOICES = ( (constants.USER_TYPE_CLEANER, 'cleaner'), (constants.USER_TYPE_CONTRACTOR, 'contractor'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) # extra fields email = models.CharField(max_length=100) phone_number = models.CharField(max_length=15) date_of_birth = models.DateField('date_of_birth') address = models.CharField(max_length=50) city = models.CharField(max_length=25) state = models.CharField(max_length=25) and set this in settings.py: # Authentication AUTH_USER_MODEL = 'web.User' How can I enable django's admin site? It's very useful for creating demo data. -
Logging User statistics in Django
I am using Django's auth_user model and wanted to log the user activities(accessed page details) in my table. I explored and figured out to use django-request module. I have installed django-request 1.5.2 for django 1.8 version. I'm getting this error "NotADirectoryError: [Errno 20] Not a directory: '/pkg/software/python/3.6.0/lib/python3.6/site-packages/django_request-1.5.2-py3.6.egg/request/migrations' and also I couldn't find this directory inside my site-packages. What could be the resolution or is there any other module that I can use to log user activities? -
How to split log file using Selenium with Django
My system already has a log file and log system error to "errors.log" When I implement Selenium to my Django project, I have got issue with Selenium log file because Selenium log was override my System log I had try many way such like add Selenium webdriver log path : webdriver.Chrome(ConstTest.CHROME_DRIVER_WINDOWS_PATH, options=options, service_log_path=ConstTest.TEST_LOG_PATH) and change my System log path LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s %(message)s' }, }, 'handlers': { 'default': { 'level': logging.DEBUG, 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOGS_DIR + '/logs.log', *changed* 'maxBytes': 1024 * 1024 * 5, 'backupCount': 5, 'formatter': 'standard', 'encoding': 'utf-8', } }, 'root': { 'handlers': ['default'], 'level': logging.DEBUG } } But It still override my log, How can I separate my log file from System with log file in Selenium ? -
How to add whatsapp,facebook and instagram share buttons on Djago site
I working on a django project ,that I would like to add whatsapp ,facebook and instagram share buttons on my post detail page.I have trie dthe djnago socia-share-widgets but none of them seeem to work for me right. Here is my code <a href="https://www.instagram.com/share?url=http://your-domain{{ request.get_full_path|urlencode }}" class="instagram-link"><i class="fa fa-instagram"></i> Instagram</a> <a href="http://www.linkedin.com/shareArticle?url=http://your-domain{{ request.get_full_path|urlencode }}&title=<your title>&summary=<your desc>&source=http://your-domain" class="linkedin-link"><i class="fa fa-linkedin"></i> Linkedin</a> <a style="background-color: green;" href="https://api.whatsapp.com/send?+254799043853=+*YOURNUMBER*&text=%20*{{ request.get_full_path|urlencode }}&title=<your title>&summary=<your desc>&source=http://your-domain*" class="youtube-link"><i class="fa fa-whatsapp"></i> Whatsapp</a> -
Multiple Django Forms in Single View: Why Does One POST Clear Other Forms?
I'm trying to implement three forms on the same page in Django. Each form has its own submit button as shown in my code. When I submit data on any one form, the data is saved but the other forms go blank upon the resulting refresh, and I get a validation error on the other forms if a field was required, for example. My hunch is that the way Django handles the POST and subsequent page refresh is what's causing the problem, and it's trying to validate all forms regardless of which submit button I press. I thought mapping the button names as shown would prevent this but clearly not, and perhaps I'll have to handle each form individually with AJAX to solve this. However I'm not SURE that's the fix, and would love it if someone could shed light on what's really happening (i.e., explain what Django is trying to do upon submit) so I can better understand how to solve. Any help is extremely appreciated. Handling multiple forms in one view in Django is anything but straightforward. Here's my code: Views.py def update_machine_view(request, brand_name_slug, mclass_slug, profile_slug): machineentry = MachineEntry.objects.prefetch_related().select_related().get(profile_slug=profile_slug) f_plate = PlateForm(request.POST or None, instance=machineentry.plate) f_dimensions = DimensionsForm(request.POST … -
I want to replace \ with / when saving filename in form_valid function of createview in django
For example, if filename is passed as below django_inflearn2 \ wm \ views.py I want to modify it like this. django_inflearn2 / wm / views.py The problem is how to get the entered information as a variable. if you know how to fix thanks for let me know code: class MyShortCutCreateView_textarea_summer_note(LoginRequiredMixin,CreateView): model = MyShortCut form_class = MyShortCutForm_summer_note def form_valid(self, form): ty = Type.objects.get(type_name="summer_note") ms = form.save(commit=False) ms.author = self.request.user # file_name = file_name_before.replace("\\","/") # ms.filename = return super().form_valid(form) -
How to write a QuerySet using F expressions on a related model's FK field in Django
In my autocomplete function I am using the following query expression to get the model field value: def CitySearch(request): if request.is_ajax(): q = request.GET.get('term','') names = City.objects.filter(name__icontains=q).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label') ... ... return HttpResponse..... How do I filter the (model) City field "name" to the FK field of related model "Country"? -
Question on customizing Django auth templates
I'm using Django 3 and Python 3.7. I've been fuddling through some of the tempalates, but I can't seem to get "success" templates to be found, for instance "password_change_done" and "password_reset_done". Both give similar Error messages. NoReverseMatch at /users/password_change/ Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. I have this in my project urls.py: urlpatterns = [ path( "users/", include( "users.urls" ) ) , path( "admin/", admin.site.urls ) , path( "", include( "main.urls" ) ) # Played with this up top, and here on the bottom. ] And in users\urls.py: urlpatterns = [ # Include default auth urls. path( "", include( "django.contrib.auth.urls" ) ) ... ] I even tried adding a TEMPLATES.DIRS value to point to user/templates. TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join( BASE_DIR, "users/templates" ) ], # With and Without this. "APP_DIRS": True, ... }, }, ] I feel like path( "", include( "django.contrib.auth.urls" ) ) should contain the correct reference, but do I need to list each one individually? How should I do that? -
Duplicate entry '1' for ForeignKey in Testing Django
I'm implement Intergration Test by Selenium for Django I have Model example like this class Product(models.Model): id = models.AutoField(max_length=11, primary_key=True) contract_id = models.IntegerField(blank=True, null=True) name= models.CharField(max_length=255, blank=True, null=True) productType= models.OneToOneField( ProductType, on_delete=models.CASCADE, db_column='product_type_id' ) productGroup = models.ForeignKey( productGroup, on_delete=models.CASCADE, related_name="ProductGroup", db_column='product_group_id' ) class Meta: db_table = 'PRODUCT' When I insert a new field to my product I got an error like this, problem is, when I insert or create new product at the first time, It still working well. But When the second times, It got error "Duplicate entry '3' for key 'product_type_id'" I think because table PRODUCT_TYPE have to a constraint product_type_id but, the value I insert has duplicate. But can I fix foreignKey constrain errors -
Shared authentication between 2 websites with different user database
im currently facing alot of problems trying to integrate an existing c# software into a new django project. The idea is to be able to use one user login , to access the other website . Is there a way to do this? Im thinking of extending the django build-in user model to contain login information to the other website , then automatically fill those fields in when the user accesses the c# website from within my django app. Is there a better way of doing this? -
No User matches the given query
I am creating a page which lets a user edits his or her name, in which the model was built on top of the AbstractUser class in Django. However, Django raised a 404 error No User matches the given query: views.py @method_decorator(login_required, name='dispatch') class ChangeInfoView(generic.edit.UpdateView): model = models.User template_name = 'myaccount/change_name.html' form_class = forms.UpdateNameForm def get_object(self): return get_object_or_404(models.User, slug=models.User.slug) def get_success_url(self): return reverse('profile', kwargs={'slug': self.object.slug}) models.py class User(util_models.CreationModificationDateMixin, util_models.UrlMixin, AbstractUser): slug = models.SlugField(unique=True) avatar = models.ImageField('Avatar', upload_to=upload_to, blank=True, null=True) recovery_email = models.EmailField(_('Recovery Email'), blank=True, null=True) about_me_email = models.EmailField(_('About Me Email'), blank=True, null=True) def __str__(self): assert isinstance(self.username, object) return self.username def save(self, *args, **kwargs): self.slug = slugify(self.username, allow_unicode=True) super().save(*args, **kwargs) self.create_thumbnail() @property def get_url_path(self): return reverse("profile", kwargs={"slug": self.object.slug}) forms.py class UpdateNameForm(UpdateFormBase): class Meta: model = User fields = ('first_name', 'last_name') def __init__(self, *args, **kwargs): super(UpdateNameForm, self).__init__(*args, **kwargs) self.helper = helper.FormHelper(self) self.helper.form_show_labels = False self.helper.form_tag = False self.helper.layout = layout.Layout( layout.Div( layout.Div( layout.Div( layout.HTML(fieldtostring("required", "autofocus", type="text", name="first_name", value="")), layout.HTML(valuetolabel("first_name", "First Name")), css_class="md-form", ), ), layout.Div( layout.Div( layout.HTML(fieldtostring("required", type="text", name="last_name", value="")), layout.HTML(valuetolabel("last_name", "Last Name")), css_class="md-form", ), ), ) ) myaccount/change_name.html <div class="modal-body" style="padding-top: 0px;"> <form method="post" action="{% url 'change_name' %}"> {% crispy form %} <div class="btn-group float-right" role="group" aria-label="Basic example"> <button type="button" class="btn … -
Feasibility of djano and elfinder interface
I'm trying to determine the software I want to use to develop a web based GUI. (For this project) The main goal of the interface is to let the user interact with files and (for example using a custom right click menu) launch Python function on the selected files. The software I was thinking to use are django and elfinder. The server would be completely implemented in django and would present the elfinder interface to select/rename/move the files. Custom menu items in elfinder would launch Python functions on the selected files. Before embarking in this project (Since I barely know how to use Flask) I'd like to have some opinions and directions on the feasibility of this project with these tools and possibly a minimal example on how to start. Thanks -
How can I check if my image went through? Getting "IOError: [Errno 90] Message too long"
I am writing an IOS app and I am currently trying to upload an image to my Django web app. I am trying to figure out how to confirm that my image when through?? When I print my request I am getting <WSGIRequest: POST '/messages/update_cert_image/'>. EDIT: with request.body i got IOError: [Errno 90] Message too long How can I save that image to my model now? For my IOS app I set up my POST like so: guard let image = ScannedCert else {return} let filename = "cert.png" let boundary = UUID().uuidString let fieldName = "reqtype" let fieldValue = "fieldupload" let fieldName2 = "userhash" let fieldValue2 = "caa3dce4fcb36cfdf9258ad9c" let config = URLSessionConfiguration.default let endpoint = "https://xxxx.xxxx.com/messages/update_cert_image/" let url = URL(string:endpoint) var urlRequest = URLRequest(url: url!) urlRequest.httpMethod = "POST" urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") let session = URLSession(configuration: config) urlRequest.addValue("Token xxxxxxx", forHTTPHeaderField: "Authorization") urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") var data = Data() data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) data.append("Content-Disposition: form-data; name=\"\(fieldName)\"\r\n\r\n".data(using: .utf8)!) data.append("\(fieldValue)".data(using: .utf8)!) // Add the userhash field and its value to the raw http reqyest data data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) data.append("Content-Disposition: form-data; name=\"\(fieldName2)\"\r\n\r\n".data(using: .utf8)!) data.append("\(fieldValue2)".data(using: .utf8)!) // Add the image data to the raw http request data data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) data.append("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"\(filename)\"\r\n".data(using: … -
Django tables - data in rows
I have a simple loop that looks at the domains and populates the sub domains column. The first column has one domain and one subdomain. So it works fine. The second domain (A6) has two subdomains (A.6.1 and A.6.2). However, the A.6.2 gets pushed to the far right. It should be under A.6.1 and A6 rows should be merged so the domain is only repeated once. So the table should be Domain Subdomain A5 A.5.1 A6 A.6.1 A.6.2 A.6.3 etc. The template tags are: <table class="table table-sm"> <tr> <th>Domain ID</th> <th>Sub Domain ID</th> </tr> {% for domain in domains %} <tr> <td>{{ domain.domain_id }}</td> {% for sub_domain in domain.subdomain_set.all %} <td>{{ sub_domain.subDomain_id }}</td> {% endfor %} </tr> {% endfor %} </table> The above code gives me this: -
Como Resolver: most likely due to a circular import
Boa noite. Sou novo em Django/Python, estou desenvolvendo um sistema onde tenho um relacionamento circular, tenho a classe pessoa e a empresa, onde uma pessoa pertence a uma empresa e uma empresa é uma pessoa. Conforme as seguintes classes: class Pessoa(models.Model): TIPO_CADASTRO_CHOICES = ( (1, ('1. FUNCIONÁRIO')), (2, ('2. CLIENTE')), (3, ('3. FORNECEDOR')), (4, ('4. TRANSPORTADOR')), ) TIPO_PESSOA_CHOICES = ( (1, ('1. JURÍDICA')), (2, ('2. FISÍCA')), ) nome = models.CharField( max_length=100 ) empresa = models.ForeignKey( on_delete=models.PROTECT, Empresa, null=True ) tipo_cadastro = models.IntegerField( ('Tipo Cadastro'), choices=TIPO_CADASTRO_CHOICES, default=3 ) tipo_pessoa = models.IntegerField( ('Tipo Pessoa'), choices=TIPO_PESSOA_CHOICES, default=1 ) class Empresa(models.Model): pessoa = models.ForeignKey( Pessoa, on_delete=models.PROTECT, verbose_name='pessoa' ) cnae= models.IntegerField( blank=True ) corporacao = models.ForeignKey( Corporacao, on_delete=models.PROTECT ) class Corporacao(models.Model): nome = models.CharField( max_length=100 ) Nesse senário ao executar makemigrations, tenho o seguinte erro: File "D:\Desenv\Projetos\Python\neosis\apps\core\models\pessoa.py", line 3, in from apps.core.models.empresas import Empresa File "D:\Desenv\Projetos\Python\neosis\apps\core\models\empresas.py", line 5, in from .pessoa import Pessoa ImportError: cannot import name 'Pessoa' from partially initialized module 'apps.core.models.pessoa' (most likely due to a circular import) -
Item setting in django model / class
What would be the best way to have a custom setter for a field that needs to be saved to the DB? For example: class Item(models.Model, ItemMixin): episode_number = models.IntegerField() season_number = models.CharField(max_length=40, default='Alula') episode_and_season_number # str(self.season_number) + str(self.episode_number).zfill(2) While it can be a property for reading purposes: @property def episode_and_season_number(self): str(self.season_number) + str(self.episode_number).zfill(2) I need to save that value to the database. What would be the suggested way to do this? -
Creating Custom Display Fields in Django Admin (that don't exist in models.py)
I have two fields in models.py numberOfUsers = IntegerField() numberOfUserCredits = IntegerField() In Django admin, instead of viewing two columns with list_display = ['numberOfUsers', 'numberOfUserCredits'] I'd like to instead clean this up a bit and concatenate these two fields for simpler viewing: str(numberOfUsers) + '/' + str(numberOfUserCredits) How can I create a custom field like this in Django admin? I could create a new field in models.py that creates this field automatically on model save, but I am wondering if there is an easier way to go about doing this. -
How do you make the fields read-only in a Django form when a specific condition is met?
Based on the following image, I am trying to make the fields category and current points non-editable when the status of the task is Finalized or Cancelled, otherwise the fields should be editable. Below is the code from my html file. {% extends "base.html" %} {% load widget_tweaks %} {% block content %} <div id="form-group"> <form method="POST" action="." enctype="multipart/form-data"> {% csrf_token %} <label>Select your category</label> {{ form.category|add_class:"card" }} <label>What's the status of the task?</label> {{ form.status|add_class:"card" }} <label>Current points:</label> {{ form.points|add_class:"card" }} <label>Finalized date:</label> {{ form.ending_date|add_class:"card" }} <button type="submit" class="btn btn-success">Send</button> </form> </div> Below is the code from my forms.py file. class TaskModelForm(forms.ModelForm): class Meta: model= Task fields = ['category', 'status', 'points'] def __init__(self, *args, **kwargs): super(TaskModelForm, self).__init__(*args, **kwargs) self.fields['status'].required = False self.fields['points'].required = False When I want to edit the contents of this form I need to verify if the status is Finalized, so the fields are non-editable, otherwise the fields should be editable and I am thinking something about: {% extends "base.html" %} {% load widget_tweaks %} {% block content %} {% if form.status.value == 'Active' %} <!--make the fields editable --> <div id="form-group"> <form method="POST" action="." enctype="multipart/form-data"> {% csrf_token %} <label>Select your category</label> {{ form.category|add_class:"card" }} ... … -
Django Form With JavaScript ReadOnly
In my django form i have java script that sets my academic field to zero if a certain time frame is selected which works fine, however i want to make that field disabled as well so the user cant remove the 0. When i set my java script to disable the field, the form validation fails and says this field is required. What do i do to accomplish this ? Thanks <script> function getTimeFrame(){ var timeframedropdown = document.getElementById('id_time_frame'); if(timeframedropdown.selectedIndex == 1 || timeframedropdown.selectedIndex == 4 || timeframedropdown.selectedIndex == 7 || timeframedropdown.selectedIndex == 8 || timeframedropdown.selectedIndex == 13){ document.getElementById('id_academic').value = 0; document.getElementById('id_academic').disabled = true; }else{ document.getElementById('id_academic').value = ""; } } document.getElementById("id_time_frame").addEventListener("change",getTimeFrame); </script> -
Updating a BooleanField via onClick
Good Evening all, apologies for what is likely a very basic question, but I've been lurking here for a few days and haven't yet come across a solution that fits. Long story short, I have a very simple model with a boolean field that I'd like to toggle via a click. The model file is: class Book(models.Model): title = models.CharField(max_length=254, default='') author = models.CharField(max_length=254, default='') genre = models.CharField(max_length=254, default='') price = models.DecimalField(max_digits=6, decimal_places=2) checkedOut = models.BooleanField(default=False) archived = models.BooleanField(default=False) I've tried inserting the following method in the relevant views / models files (both to no avail): def check_in_out(self): if self.checkedOut == False: self.checkedOut = True else: self.checkedOut = False self.save() I have the following in the urls: url(r'^$', check_out, name='check_out') and the html for the relevant button is: <button class="check_btn button button-outline" method="post" type="submit" onClick="{% url 'check_out' %}"> <i class="fas fa-book"></i> </button> I'm sure that I'm missing something obvious - or am trying to oversimplify a more complex task, but nothing seems to work. I also tried following the advice here Change a boolean value after a click on a button in Django but similarly am having no joy. -
Fetch calls to RESTful API fail to authenticate on iOS after React Native 0.61 update
I'm working on a React Native app which needs to make API calls to a RESTful API built on the Django REST framework. To authenticate, our API has a login endpoint which sends back a sessionid cookie in the header, which we then send back in future request headers to receive user-specific information. On Android this works as expected, however on iOS when sending exactly the same request after successfully logging in the server throws an error due to the user being unauthenticated. The only noticeable difference in these tests is that on iOS the server returns an empty sessionid after making the second call (sent with a valid sessionid): "headers": Object { ... "Cookie": "sessionid=\"\"; ..." } We recently updated to Expo SDK 36, which includes an update to React Native 0.61. Prior to this update, both Android and iOS versions worked as expected, however I cannot be sure this was the direct cause as there was a ~2 week break over Christmas directly after updating before discovering the issue. This snippet shows how we get the cookie when making a request (currently avoiding using extra libraries to simplify the process): response = await fetch(requestConfig.url, requestConfig) .then(result => { … -
Cannot connect to broker error, connection reset by peer
When I tail my celeryd I get: consumer: Cannot connect to amqp://guest:**@10.0.1.248:5672//: [Errno 104] Connection reset by peer. Trying again in 32.00 seconds... When I tail my flowerd I get: [DEBUG 2020-01-13 22:31:39,900] events.py [:133] on_enable_events: Failed to enable events: '[Errno 104] Connection reset by peer' I have tried both sudo invoke-rc.d rabbitmq-server start and sudo rabbitmqctl start_app I have been working on this issue all day and can't seem to figure it out. It started off updating my instance where I had to change my BROKER_URL to amqp://guest:**[NEW_INSTANCE_IP]:5672 and ever since nothing has been working right. I am fairly new to utilizing rabbitmq, celery and supervisord. Any help would be greatly appreciated. Thank you.