Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error while try to login in django admin database
after running the server when I try to login Django admin page I'm getting this error "unable to open database file". here is the important part from my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / "db.sqlite3"), } } How to solve this problem? -
How to put Original File to Django
I am using Reactjs as FrontEnd, Django as Backend. I am trying to push image as original file by using Antd but it doesnt work all of remain fields are posted but image is not. It return null, sometimes return error 404 this is my state: const [state, dispatch] = React.useReducer(newAvatar, { status: 'idle', clear: false, message: null, fileImg: [], users: '', initialValues: { username:'', //user.username, email:'', // user.email, name:'',// user.name, phone:'',// user.phone, birthday:'',// user.birthday, gender:'', //user.gender, address:'', //user.address, image:'',// user.userImage, } }) const [form] = Form.useForm() const history = useHistory() const authenticate = useAuthenticate() const userid =user.id; and this is my onfinish const onFinish = async values => { let formData = new FormData() for (const key in values) { formData.append(key, values[key] ?? '') } formData.append('userId', user.id) formData.append('name',values.name) formData.append('username',values.username) formData.append('phone',values.phone) formData.append('birthday',values.birthday) formData.append('gender',values.gender) formData.append('address',values.address) formData.append('email',values.email) // if(values.image!= null) { // formData.append('userImage',values.image) // } // state.fileImg.forEach((file, i) => formData.append(`images${i}`, file)) try { await axios.patch(`/api/users/${userid}/`, formData, { headers: { Authorization: `Bearer ${cookies['gp_token']}` } }) .then(res => { console.log(res.data) authenticate({user: res.data, token: cookies['gp_token']}) }) form.resetFields() dispatch({ type: 'upload_success' }) } catch (error) { dispatch({ type: 'upload_fail' }) } finally { window.scrollTo(0, 0) modal.destroy() } } please support me thank all of you a … -
Change Column Name on html table created via pandas
I created a panda dataframe from django models. A table was created. I want to rename the column names which are in th tag. How can I do it? Here is what come. Image is in the link. https://ibb.co/s1VxRF2 @login_required def totaldonation(request): payments = Payment.objects.all().values() df = pd.DataFrame(payments) dada = { "df": df.to_html(index=False, classes='table').replace('border="1"','border="0"') -
how break a celery task inside task
I an using celery with django.inside a forloop , each turn a value sets in db for a relationship lawyers=Lawyer.objects.filter(consultation_status=True) for idx,lawyer in enumerate(lawyers): if(consultation.lawyer): break change_offered_lawyer.apply_async((id,lawyer.id),countdown=idx*60) each turn in the loop inside task i check the condition and my goal is if the condition terminated then break all those tasks. @app.task def change_offered_lawyer(consulation_id,consulator_id): consulation=ConsultationOrder.objects.get(id=consulation_id) consulator=Lawyer.objects.get(id=consulator_id) if(consultation.lawyer): #break all tasks consultation.offered_lawyer=consulator consultation.save() -
Page not found error when clicked on the image url coming in the get api in Django
I have a simple get api built using Django Rest Framework. It is getting all the food items from the model, Menu. It consists of an image field. The api response is successful and I am getting an image URL in the image field, but when I click on that url, the image is not shown in the new tab. I have done a few projects and as far as I remember, it should show the image on the new tab. Due to this, the image is not shown in the frontend which is done in Reactjs. The backend in served in Heroku for now. The url is similar as follows: https://example.herokuapp.com/api/menus The api response in local is as follows: And when I click on the both image and image_url, it shows the follows: I added image_url just to see if it works, but it didnt work as well. My model: class Menus(models.Model): category = models.CharField(max_length=50,choices=CATEGORY,default='main courses') food_name = models.CharField(max_length=100,blank=True, null=True) image = models.ImageField(upload_to='media/pictures',null=True) rating = models.FloatField(blank=True, null=True) description = RichTextField(blank=True, null=True) price = models.FloatField(blank=True, null=True) My serializers: class MenusSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField('get_image_url') def get_image_url(self, obj): request = self.context.get('request') image_url = obj.image.url return request.build_absolute_uri(image_url) class Meta: model = Menus fields … -
The current path, products/new/, didn't match any of these - Page Not Found
I just installed python 2.2.20 and now when running a Django project I get a page not found error. I'm not sure why I'm getting this error when I try to navigate to products/new -
django - choices from __init__ are not loading in the form
I am using __init__ to build my form choices from parameters passed from the view. It looks like my choices are built correctly when I do print(choices), but the form is not loading any choices. There isn't even a widget for it showing. I do not get any errors. I've used similar code in other views which worked, which is one reason why this one is really confusing me. I did see that print("ok") never gets printed to the shell, while print("else") does get printed view def newobjtoassess(request, assess_pk): user = request.user assessment = Assessment.objects.get(pk=assess_pk) course_pk = assessment.course.pk context['assessment'] = assessment form = ObjToAssessmentForm(user=user, course_pk=course_pk) if request.method == 'POST': print("ok") form = ObjToAssessmentForm(request.POST, user=user, course_pk=course_pk) if form.is_valid(): f = form.cleaned_data objective = f.get('objective') assessment.objectives.add(objective) assessment.save() return HttpResponseRedirect(reverse('gradebook:assessupdate', args=[assess_pk])) else: context['form'] = form return render(request, "gradebook/newobjtoassess.html", context) else: print("else") form = ObjToAssessmentForm(user=user, course_pk=course_pk) return render(request, "gradebook/newobjtoassess.html", context) form class ObjToAssessmentForm(forms.Form): objective = forms.ChoiceField(label='Learning Objective', choices=[]) def __init__(self, *args, **kwargs): user = kwargs.pop('user') my_course = kwargs.pop('course_pk') super(ObjToAssessmentForm, self).__init__(*args, **kwargs) choices=[(o.id, str(o)) for o in Objective.objects.filter(user=user, course=my_course)] print(choices) self.fields['objective'] = forms.ChoiceField(choices=choices) template {% extends 'base-g.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} <div class="container"> <div class="row"> <div … -
How to verify a client side certificate in django?
I am new to django and working on my first project. The requirement I have infront of me is of mutual authentication for client and server. I am not able to figure out how to verify the client side certificate. It is generated using openssl and we don't have a domain yet. I am using Windows OS and django3.2.5. Will I have to setup Nginx for it? Or can it be done without it? Because I think I cannot setup Nginx on Windows without docker or Linux VM. Any help will be greatly appreciated. Thank You in advance. -
url to fetch with parameter for django view
I'm facing a problem with my javascript code when trying to use AJAX instead of href link. I need to hit a django url that looks like this (Django 2.2): path('one-time/<str:product_url>/', OneTimeProductView.as_view(), name='one_time_product') the origial code in the django template was: <a href="{% url 'one_time_product' product %}">{{product}}</a> I now want to use ajax call to make the whole process opened inside of a modal. In my javascript code my fetch function looks like this: function handleAccess(){ var url = "{% url 'one_time_product' product %}" ; fetch(url, { method: "POST", headers: { "X-CSRFToken": '{{csrf_token}}', "Accept": "application/json", "Content-Type": "application/json" } }) .then (response => { response.json(); }) .then (data => { console.log(data); }) }; I know i'm missing something related to the params in the url variable but I just don't know how to add it properly so that i fit the url path. This is the error that I get when I hit the button NoReverseMatch at /one-time/ Reverse for 'one_time_product' with no arguments not found. 1 pattern(s) tried: ['one\-time\/(?P<product_url>[^/]+)\/$'] How should I write the url in the fetch function ? I will appreciate and anyone can point me into the right direction here. Thanks -
Ids incremented twice during import-export (Django)
I am using Django-import-export library, I am facing problem while uploading data in json/csv file. when I upload data file via django-admin, id field increases twice? how to solve this problem? thanks -
TemplateDoesNotExist at / boards/home.html
I'm creating my first site with Django and following a tutorial. Tutorial here. The trouble I'm having is when attempting to load the site using the standard http://127.0.0.1:8000/, I get the error TemplateDoesNotExist at / boards/home.html Django says it's trying to follow this path: "C:\Users\myuser\Desktop\Development\myproject\myproject\boards\templates\boards\home.html (Source does not exist)" When I put that path directly into my file explorer it loads the file with no issues. Here is my urls.py: from django.urls import path from boards import views urlpatterns = [ path('', views.home, name='home'), path('admin/', admin.site.urls), ] And my views.py: from .models import Board def home(request): boards = Board.objects.all() return render(request, 'boards/home.html', {'boards': boards}) And settings.py has 'boards' (the name of the app) under the INSTALLED_APPS heading. My file structure is like so: I hope somebody can help. Just ask if I've missed anything. -
Can't get a true if conditional to trigger in Django Template
I'm trying to stylize my different blog post tags by running an if conditional that simply checks for the name of the tag and executes the style I want for that specific tag. It appears the condition should check True, but only the code under the else clause is being executed. In the example below, my "News" tag should have the class badge badge-primary, but instead it's falling under the else and applying badge badge-secondary. I've tried upper and lower case. I've also tried with and without the counter, which is there for other purposes. Still, no luck. Template: {% for tag in object.tags.all %} {% if forloop.counter|divisibleby:"2" %} {% if tag == "News" %} <li> <span class="badge badge-primary">{{ tag }}</span> </li> {% else %} <li> <span class="badge badge-secondary">{{ tag }}</span> </li> {% endif %} {% endif %} {% endfor %} When replacing: {% if tag == "News" %} With: {% if tag in object.tags.all %} It works, and the tag will populate the first span class as it should. I believe this tells me that the syntax I'm using is correct. For some reason my == conditional isn't being seen True, even though it should be. To check things … -
how to store recent data and after that when i call function again then the previous and recent data addition of both gets store
here what i want to do is when i search something add that thing in my list then that data shown in the 'myTable1' add after that when I enter some numbers in its coresponding input then that data is store in veriable and after that output is shown in next page in next page also if i select some data and its value and add this and last values and then show the output on this new list. And in my code can fetch data in first time but in second time it is not adding the last list only showing the newest one. plz help me and also explian this why this is happening. thanks in advance. <body> <div class="container"> <div class="tabble"> <div class="col"> <div> <label class="ac_trigger" for="ac1"> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search For Food Names.." title="Type in a name"> &nbsp;<i class="fa fa-search"></i> </label> </div> <br> <div class="ac_container" id="div1"> <table id="myTable"> <tr class="header" id="heading" style="display: none;"> <th style="width:80%;">Name</th> <th style="width:20%;padding: 4px;">Select</th> </tr> {% for a in foodlist2 %} <tr style="display: none;"> <td>{{a|title}}</td><td style="text-align:center"><input id="btn" type="button" value="Add" name="{{a}}" onclick="add_item(this, this.parentNode.nextSibling.nextSibling)"></td> <td style="display: none;text-align: center;"><input id="btn" type="button" name="{{a}}" value="Remove" onclick="remove_item(this,this.parentNode.previousElementSibling)"></td> </tr> {% endfor %} </table> </div> <div class="ac_container"> <table id="myTable1"> … -
Locked out from my server after a few hours ssh
I am trying to deploy my django-mysql application. I am successfully able to deploy however after a few hours I cannot ssh into the server + access the site. ssh: connect to host port 22: Operation timed out This deploy issue is happening to me twice and trying to figure out why. Steps that I have taken to deploy. sudo yum install -y python3 python3-devel gcc python3 -m venv env and source env/bin/activate Upload project to /home/user pip3 install -r requirements.txt Install and cofigure my sql, migrate sudo yum install -y httpd httpd-devel pip3 install mod_wsgi sudo vi /etc/httpd/conf.d/my_conf.conf LoadModule wsgi_module /home/user/my_project/env/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so WSGIScriptAlias / /home/user/my_project/my_project/wsgi.py WSGIPythonHome /home/user/my_project/env WSGIPythonPath /home/user/my_project DocumentRoot /home/user/my_project/ <Directory /home/user/my_project/my_project> <Files wsgi.py> Require all granted </Files> </Directory> <Location /lock> AuthType Digest AuthName "Private" AuthUserFile /etc/httpd/password/digest Require valid-user </Location> chmod 755 /home/user sudo service httpd start and sudo systemctl enable httpd.service Setup digest authentication using htdigest Able to deploy but can't ssh into the server + access the site after a few (10~) hours Is there anything that I am doing wrong? Any help is appreciated. -
'DatabaseOperations' object has no attribute 'select' error when integrating Azure SQL database with django
I recently changed from using a Postgres / PostGIS database backend for my Django application to a SQL database on Azure. I have a geometry column in my data table. I can query the geometry column from Azure Data Studio just fine, and using raw SQL queries in my view. However, when I try to return a view using Django's ORM, I get this error (longer traceback below): AttributeError at /building/1/ 'DatabaseOperations' object has no attribute 'select' Request Method: GET Request URL: http://localhost:8000/building/1/ Django Version: 2.1.15 Exception Type: AttributeError Exception Value: 'DatabaseOperations' object has no attribute 'select' From what I can see, it seems like it is a settings / config issue and most posts say to properly configure Postgis, however I need to use an Azure SQL database, not Postgis. Here are my settings: DATABASES = { "default": { "ENGINE": "sql_server.pyodbc", "NAME": "Buildings", "USER": "BuildingsUser", "PASSWORD": "*************", "HOST": "buildings-test-db.database.windows.net", "PORT": "1433", "OPTIONS": { "driver": 'FreeTDS', 'host_is_server': True, # 'MARS_Connection': 'True', }, }, } Has anyone successfully configured an Azure database with geospatial columns for a django app, and used the Django ORM? Maybe I need a different engine for a SQL server db with geospatial columns? I would really … -
Herokuapp not updating my website content
I changed the meta content for my Django herokuapp and deployed again, but now still it's showing the previous content. Do I need to clear the cache? If so how to do that? Is that possible from heroku bash? GitHub is my repository. -
How to get django-tenants-celery-beat to schedule periodic tasks
I am a little newer to Celery and Celery Beat but I already have tenant_schemas_celery running in my project: import os from celery.schedules import crontab from tenant_schemas_celery.app import CeleryApp as TenantAwareCeleryApp from config import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = TenantAwareCeleryApp() app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) In a apps.periodic_testing.tasks.py file I have: from celery.schedules import crontab from celery.utils.log import get_task_logger from django_tenants_celery_beat.utils import generate_beat_schedule from config.celery import app logger = get_task_logger(__name__) @app.task def add(x=1, y=2): z = x + y print(z) app.conf.beat_schedule = generate_beat_schedule( { "tenant_task": { "task": "app.tasks.add", "schedule": crontab(minute=0-59), "tenancy_options": { "public": False, "all_tenants": True, "use_tenant_timezone": True, } }, "hourly_tenant_task": { "task": "app.tasks.add", "schedule": crontab(minute=0-59), "tenancy_options": { "public": False, "all_tenants": True, "use_tenant_timezone": False, } }, } ) But I can't seem to get the scheduler working. Any idea of what I could be doing wrong? -
Json data not saving in django database Admin
I am building a BlogApp and I am trying to access user location through geoplugin BUT it was sending through json so i made a view to send json data to database BUT json data is not saving in Database (Admin). When i click on link then it is showing :- 'NoneType' object has no attribute 'json' BUT then i use json.loads then it is showing :- the JSON object must be str, bytes or bytearray, not NoneType models.py class Location(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) city = models.JSONField() views.py def jsonLocation(request): r = request.POST.get('http://www.geoplugin.net/javascript.gp') # data = json.loads(r) data = r.json() for x in data: title = x["geoplugin_city"] user = request.user addin = Location.objects.create(city=title,user=request.user) addin.save() return HttpResponse("Successfully submitted!") I have seen many answers but did't find any solution. And it is still not saving in database. Any help would be Appreciated. -
how to auto scale django project in Elasticbeanstalk?
I have my Django setup on Elastic beanstalk, it's working properly considering on single instance. But when tested with ALB, the auto-scaled instance appears to be missing application code when it gets launched which it should have taken from s3 I assume (I had used console and uploaded my source bundle directly). I want to have source code reflected in autoscaled instance. What am i missing, is there any way for it or to automate this? -
Convert sensor SQL into json in Python
mydb = mysql.connector.connect( host="db-instance.rds.amazonaws.com", user="root", passwd="test", database="test" ) mc = mydb.cursor() sql = "INSERT INTO robot1_sensor (robot_id, x, y, ultrafine_dust, fine_dust, co2, formaldehyde, co, no2, radon,tvoc,temperature,humidity) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"; def air_info_recv(msg) : global mc global sql global mydb global robot_id global x global y print ("sub0000") air_info_dict = dict() print(msg.Dust_PM2_5_ugm3) print ("sub111") Fine_dust = msg.Dust_PM10_ugm3 Ultrafine_dust = msg.Dust_PM2_5_ugm3 CO2 = msg.CO2_ppm Formaldehyde = msg.HCHO_ugm3 CO = msg.CO_ppm NO2 = msg.NO2_ppm Radon = msg.Rn_Bqm3 Organic_compounds = msg.TVOCs_ugm3 Temperature = msg.temp_celcius Humidity = msg.hum_RHp print ("sub2222") val = (robot_id,x,y,Ultrafine_dust,Fine_dust,CO2,Formaldehyde,CO,NO2,Radon,Organic_compounds,Temperature,Humidity) mc.execute(sql, val) print ("sub33333") mydb.commit() print(mc.rowcount, "insert record") I want to change the python sql above to json and send it to server api. Server api is working with django. I need your help on how to change it. And if there is a good way, please recommend it. Thank you. -
django ajax ajaxify non-database image upload
I have some code from somewhere that let's the client display an uploaded image that is not saved to the database on the page. Is it possible to make it do so with ajax? I tried, but I clearly don't know what i'm doing or if it's even possible or if there's client safe way to do so. I keep getting fakepath and the name of the image. Here is the code without my embarrassing ajax attempts: views.py def upload_render(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['image'] data = file.read() # Calling .decode() converts bytes object to str encoded = b64encode(data).decode() mime = 'image/jpeg;' context = {"image": "data:%sbase64,%s" % (mime, encoded), 'form': form} return render(request, 'upload_render.html', context) else: form = FileForm() return render(request, 'upload_render.html', {'form': form}) upload_render.html <h2>Image upload</h2> <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% if image %} <img src="{{ image }}"> {% endif %} forms.py class FileForm(forms.Form): image = forms.ImageField(help_text="Upload image: ", required=True) -
Django: Model does not appear on admin panel
This is the model that I want to show on the admin panel. I'm registering the model via admin.py file with admin.site.register(Ad). I tried to re-write the register line twice, and an exception appeared that the model is already registered. class Ad(AdModel): plate = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=500) ad_type = models.CharField( max_length=255, choices=AdTypes.get_choices(), default=AdTypes.OFFERING, ) price = models.PositiveIntegerField( default=0, help_text='In cents' ) location = models.CharField( max_length=255, choices=AdLocations.get_choices(), default=AdLocations.VILNIUS, ) user = models.ForeignKey(User, on_delete=models.PROTECT) approved_date = models.DateField(null=True, blank=True) approved_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name='approved_by', null=True ) The two base models: class UUIDBaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) class Meta: abstract = True class AdModel(UUIDBaseModel): expires_at = models.DateTimeField(null=True) is_draft = models.BooleanField(default=False) is_active = models.BooleanField(default=False) class Meta: abstract = True This is really strange, maybe that could be the problem because of the naming 'Ad'? I have a serializer for this model and everything works just fine, but the admin panel doesn't want to display it. views.py class AdCreateViewSet(ModelViewSet, CreateModelMixin): serializer_class = AdCreateSerializer permission_classes = (AllowAny,) filter_backends = [DjangoFilterBackend] search_fields = ('plate', 'description', 'user__email') queryset = Ad.objects.select_related('user') def perform_create(self, serializer): user = User.objects.first() serializer.save(user=user) # self.request.user) serializers.py class AdCreateSerializer(CustomAdSerializer): class Meta: model = Ad exclude = … -
Javascript - Editing Form with Fetch
I'm trying to edit an existing form on my site, and save the edits using Javascript (without requiring a refresh of the page). I'm using Django as well. So far, when the user clicks 'edit' on the page, the form appropriately appears, showing the information already saved there. But when I click 'save' I get a 404 error. The issue is in the Javascript function edit_post. I'm not sure if I have used stringify correctly either, I'm new to using Javascript with Django. Any help is appreciated. function edit_handeler(element) { id = element.getAttribute("data-id"); document.querySelector(`#post-edit-${id}`).style.display = "block"; document.querySelector(`#post-content-${id}`).style.display = "none"; // everything above this works and opens up the form for editing edit_btn = document.querySelector(`#edit-btn-${id}`); edit_btn.textContent = "Save"; edit_btn.setAttribute("class", "text-success edit"); if (edit_btn.textContent == "Save") { edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here edit_btn.textContent = "Edit"; edit_btn.setAttribute("class", "text-primary edit"); }} function edit_post(id, post) { const body = document.querySelector(`#post-content-${id}`).value; fetch("/edit_post/", { method: "POST", body: JSON.stringify({ body:body }) }).then((res) => { document.querySelector(`#post-content-${id}`).textContent = post; document.querySelector(`#post-content-${id}`).style.display = "block"; document.querySelector(`#post-edit-${id}`).style.display = "none"; document.querySelector(`#post-edit-${id}`).value = post.trim(); }); } Relevant html - this is inside a card, for the post itself in the html file: <span id="post-content-{{i.id}}" class="post">{{i.text}}</span> <br> <textarea data-id="{{i.id}}" id="post-edit-{{i.id}}" style="display:none;" class="form-control textarea" row="3">{{i.text}}</textarea> <button class="btn-btn primary" data-id="{{i.id}}" id="edit-btn-{{i.id}}" … -
login manually fails first time in Django
I am trying to authenticate and login user manually, but it fails first time and going to login page asking for the credentials again, but next time onwards it works, is there anything related to session I should add, any help is appreciated, here is my code def admin_login(request): user = authenticate(username='admin_user', password='admin_user') if user is not None: login(request, user) return redirect('xxxx') else: return redirect('xxxx') return render(request, 'xxxx.html', {}) -
Calculating a field value based on PK in Django
Goal: Set customer_number to a calculated value of b_country + id + 10000. models.py class Customer(models.Model): id = models.BigAutoField(primary_key=True) customer_number = models.CharField("Customer #", max_length=10, default=0) b_country = models.TextField("Country", max_length=2, choices=COUNTRY_OPTIONS) @property def get_customer_number(self): a = self.b_country b = (self.id + 10000) return a + str(b) def save(self, *args, **kwarg): self.customer_number = self.get_customer_number super(Customer, self).save(*args, **kwarg) Issue: When the form is submitted to create a new customer (new record) then I get the following error: a 'CA' self Error in formatting: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'> When I already have a record (updating and existing Customer's info) then the code works fine. It is my understanding that it isn't able to get the id as it is still validating the data before being sent to the model, hence no Customer.id to pull for this instance. Question: Is there a cleaner way of setting a customer_number that is based on the PK?