Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I load django user data into user edit form in permission escalation safe environment
I am trying to create a profile edit form in django for Users in a way that they cannot set themselves as superuser or staff. This is my first learning project in django and so far I have followed https://docs.djangoproject.com/en/4.1/topics/forms/ to set everything up. in views.py @login_required def edit_profile(request): user = request.user if request.method == 'POST': form = edit_profile_form(request.POST) if form.is_valid(): if user.is_authenticated: try: user.first_name = form.cleaned_data['firstname'] user.last_name = form.cleaned_data['lastname'] user.email = form.cleaned_data['email'] user.username = form.cleaned_data['username'] user.save() except Exception as e: return HttpResponse(e) return render(request, 'index.html') else: #Get data ready for form data = {'firstname': user.first_name, 'lastname': user.last_name, 'email': user.email, 'username': user.username} form = edit_profile_form(data) return render(request, 'edit_profile.html', {'form': form} ) in forms.py from django import forms class edit_profile_form(forms.Form): firstname = forms.CharField(label='First name', max_length=100,) lastname = forms.CharField(label='Last name', max_length=100) email = forms.EmailField(label='Email', max_length=100) username = forms.CharField(label='Username', max_length=150) def __init__(self, *args, **kwargs): data = kwargs.get('data', None) super(edit_profile_form, self).__init__(*args, **kwargs) if data: self.fields['firstname'].initial = data['firstname'] self.fields['lastname'].initial = data['lastname'] self.fields['email'].initial = data['email'] self.fields['username'].initial = data['username'] in edit_profile.html {% extends 'base.html' %}{% load static %} {% block content %} <link href="{% static 'css/edit_profile.css' %}" rel="stylesheet" /> <main class="profile"> <form method='POST'> {% csrf_token %} <h1> Profile editor </h1> {{ form }} <input type='submit' value='Submit' class='btn … -
uploaded images not displayed in Django
I'm developping a django app but recently, I faced a challenge of images files uploaded in django admin that are not being displayed on pages, I tried every solution given here on the platform but none of it gave me a solution, plz does someone can help with this issue because it is been a while working on without a result. These are my models class House(models.Model): image_house = models.ImageField(upload_to='Images/', default='Images/house.png') # Cars property model class Car(models.Model): image_car = models.ImageField(upload_to='Images/', blank=True, default='Images/car.png') # Fields property model class Land(models.Model): image_land = models.ImageField(upload_to='Images/', blank=True, default='Images/land.png' ) and I set this in settings.py STATIC_URL = '/static/' # Media root and urls MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And that' how I called the uploded picture from the model in Index.html <img src="{{ house.image.url }}" class="card-img-top" alt="..."> in my project urls I added urlpatterns = [ path('admin/', admin.site.urls), path('', include('realest_app.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) -
Reason given for failure: CSRF token from POST incorrect.?
Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token from POST incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting. please solve this? Reason given for … -
How do I use my coding skills for the greater good?
I am 17 year old African kid who knows HTML,CSS,JS(from freecodecamp) and currently learning django for making fullstack applications. I have no idea of what projects to make of them that will help my society and community. After solving the problem I want to write an essay about it when I apply to colleges and universities. something doable and takes few months to fully launch, since I am a senior I don't have much time in my hand. Please be specific don't give me only catagories. Ideas I got from my friends,family and internet: website for non-profit banking system government system school club websites -
Fixing "missing 1 required positional argument: 'id'" error when sending data from Django Form using Ajax
I have a Django Form where users inserts numeric values. I am sending the Ajax to a url but I keep receiving: TypeError: addlog() missing 1 required positional argument: 'id' I have tried to add the id in the url I got: Reverse for 'addlog' with arguments '(2,)' not found. 1 pattern(s) tried: ['workout/addlog/\\Z'] Here is the views: def addlog(request, id): workout = get_object_or_404(Workout, id=id) url = request.META.get('HTTP_REFERER') active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id) if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == 'POST': form = LogForm(request.POST) if form.is_valid(): data = Log() data.log_workout = request.POST.get('log_workout') data.save() context = { 'log_workout': data.log_workout, 'id': workout.id, } html = render_to_string('my_gym/log_form.html', context, request=request) return JsonResponse({'form': html}) else: print("The errors in addlog:",form.errors.as_data()) else: print("What happened??") return HttpResponseRedirect(url) Here is the form: <form class="review-form" action="{% url 'my_gym:addlog' object.id %}" method="post"> {% csrf_token %} </form> Here is the script: <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click','#submitlog', function(event){ event.preventDefault(); var log_workout = $('#id_log_workout').val(); $.ajax({ type:'POST', url:'{% url 'my_gym:addlog' object.id %}', data:{'log_workout' : log_workout, csrfmiddlewaretoken':'{{csrf_token}}'}, dataType:'json', success:function(response){ $('#log_form').html(response['form']), console.log($('#log_form').html(response['form','div'])); }, error:function(rs, e){ console.log(rs.responseText); }, }); }); }); </script> Here is the url: path('workout/addlog/<int:id>', addlog, name='addlog'), My question How can I fix this error knowing that I tried changing the workout.id to object.id still same error. -
CSRF Failed | CSRF cookie not set
I'm using class based views to render a template. In that same class, I also have a post request to allow for the submission of a form. However, when I submit the form, I get the CSRF cookie not set error. I did use the {% csrf_token %} but still doesn't work. Here is my code: class SignIn(View): def get(self, request): # email = request.POST['email'] # password = request.POST['password'] template = loader.get_template('signin.html') logging.info(request) return HttpResponse(template.render()) def post(self, request): email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] template = loader.get_template('signin.html') logging.info(request.__dict__) logging.info(password1) logging.info(email) if User.objects.filter(email=email).exists(): messages.info(request, 'E-mail Exists!') return redirect('signup') elif password1 != password2: messages.info(request, 'PASSWORD DOESNT MATCH') return redirect('signup') new_user = User.objects.create_user(email, email, password1) return HttpResponse(template.render()) This is my template: <html> <div> <p> Signup </p> <form method = "POST" action="/signup"> {% csrf_token %} username: <br/> <input type="text" name="email" /> <br/> Password: <br/> <input type="password" name="password1" /> <br/> confirm Password: <br/> <input type="password" name="password2" /> <br/> <input class ="btn btn-primary" type="submit" value= "signup" /> <br/> </form> </div> </html> My urls.py: from django import views from django.urls import path from .views import SignUp, SignIn, Index urlpatterns = [ path('', Index.as_view(), name='Index'), path('signup', SignUp.as_view(), name='SignUp'), path('signin/', SignIn.as_view(), name='SignIn') ] -
Django : FieldError at /editstu/121
Error : Cannot resolve keyword 'id' into field. Choices are: Age, Course_ID, DoB, Grade, Student_ID, Student_Name My function in views.py def Editstu(request,id): editstuobj = Student.objects.get(id=id) return render(request, 'editstu.html',{'Student':editstuobj}) My urls.py urlpatterns = [ path("admin/", admin.site.urls), path('',views.showStudent), path('InsertStudent',views.InsertStudent,name="InsertStudent"), path('Insertcour',views.InsertCourse,name="InsertCourse"), path('editstu/<int:id>',views.Editstu,name="Editstu"), path('editcour/<int:id>',views.Editcour,name="Editcour"), # path('Update/<int:id>',views.updateemp,name="updateemp"), path('Deletestu/<int:id>',views.Deletestu,name="Deletestu"), path('Deletecourse/<int:id>',views.Deletecourse,name="Deletecourse"), ] My Index.html <td><a href="editstu/{{result.Student_ID}}">Edit</a></td> <td><a href="Deletestu/{{result.Student_ID}}" onclick="return confirm ('Are you sure to delete the record?')">Delete</a></td> I checked the function if it is declared properly but no luck. I'm new to Django. It says error is 'id' but it should be fine. Please help if anyone can. -
'node with name "rabbit" is already running on host' even after killing the processes
Whenever I try to run a rabbit server, it meets me with this error: ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R" I've read that I should kill the processes of rabbit by using rabbitmqctl stop But I still get the error, What else can I do I am on windows 10 Here is my full error 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> BOOT FAILED 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> =========== 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R" 2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> BOOT FAILED =========== ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R" 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> supervisor: {local,rabbit_prelaunch_sup} 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> errorContext: start_error 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> reason: {duplicate_node_name,"rabbit","DESKTOP-BKRTA3R"} 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> offender: [{pid,undefined}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {id,prelaunch}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {mfargs,{rabbit_prelaunch,run_prelaunch_first_phase,[]}}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {restart_type,transient}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {significant,false}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {shutdown,5000}, 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> {child_type,worker}] 2022-11-11 16:46:04.017000-08:00 [error] <0.131.0> 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> crasher: 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> initial call: application_master:init/4 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> pid: <0.129.0> 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> registered_name: [] 2022-11-11 16:46:04.017000-08:00 [error] <0.129.0> exception exit: {{shutdown, 2022-11-11 16:46:04.017000-08:00 [error] … -
Python Django: getting data from modal gives <built-in function id> error
I'm trying to get a value from a modal, that gets the value using jQuery from a list. Let's explain. I have a list of objects in an HTML page using a for loop, and in each row, there is a delete button. This delete button launches a confirmation Modal. To get the id of the row and use it in the Modal, I use jQuery: {% for a in objects %} [...] <td><button type="button" class="delete-button" data-name="{{ a.id }}" data-bs-toggle="modal" data-bs-target="#deleteModal">Delete</button></td> [...] {% endfor %} [...] <div class="modal fade" id="deleteModal"> [...] <form action="{% url 'delete_object' %}" method="post"> {% csrf_token %} <input type="hidden" name="object_id" name="object_field" /> <button type="submit">Delete</button> [...] <script> $('.delete-button').click(function() { $('#object_id').html($(this).data('name')) }) </script> Without explaining the urls.py part, let's get straight to the view, which is quite simple: def cancel_request(request): _id = request.POST.get("object_id") obj = Object.objects.get(id=id) obj.status = "Annulé" obj.save() return redirect("home") When I run the modal, I make sure I can see the id value getting in the modal, but when I try to put it in an input, I cannot see it anymore. If I put it in an h5 tag for example: <h5 class="modal-title" id="request_id" name="requestid_kw"></h5>, it shows on the modal, but still does not get … -
Post_save method in django
I've have stuck in a problem where if both the person follows the each other only then it should make them friends. I'm planning to use Django signal's post save method for this. But I'm not able to make any progression in it .Please help me on this .Thanks in advance and do refer the code below and sorry for bad coding. Models.py: class Follow(models.Model): Follower=models.ForeignKey(User, models.SET_NULL,null=True,related_name='from_user_followers',blank=True) Followe=models.ForeignKey(User,models.SET_NULL,null=True,related_name='to_user_followers',blank=True) created=models.DateTimeField(default=now) @receiver(post_save, sender=Follow) def create_friend(sender, instance, created, **kwargs): if created: see_followe_is_following_back = Follow.objects.filter(Followe=instance.Follower, Follower=instance.Followe) see_follower_is_following_back = Follow.objects.filter(Follower=instance.Followe, Followe=instance.Follower) try: if str(instance.Follower) == str(see_follower_is_following_back) and str(instance.Followe) == str(see_followe_is_following_back): create_friends= Friends.objects.update_or_create(from_user=instance.Followe , to_user=instance.Follower) return create_friends else: pass except Exception as e: return str(e) else: pass class Friends(models.Model): from_user=models.ForeignKey(User, models.SET_NULL,null=True,related_name='from_user_friends',blank=True) to_user=models.ForeignKey(User,models.SET_NULL,null=True,related_name='to_user_friends',blank=True) created=models.DateTimeField(default=now) -
In Heroku , python setup.py egg_info did not run successfully. error in troposphere setup command: use_2to3 is invalid
So, I am trying to deploy this django project on the Heroku platform and while making all the requirements running on the local server while this code is added to Heroku and it installs it on its server, It throws an error and didn't resolved, Even after lot of tries. Problem is with the setup.py installation and troposphere. I tried commands like:- pip install --upgrade setuptools. But this also didn't worked it gave the same error. For reference dropping my requirements:- argcomplete==1.12.3 asgiref==3.4.1 autopep8==1.5.7 awsebcli==3.20.3 boltons==21.0.0 boto3==1.18.16 botocore==1.23.54 cachetools==4.2.2 cement==2.8.2 certifi==2021.5.30 cfn-flip==1.2.3 charset-normalizer==2.0.4 click==8.0.1 colorama==0.4.3 dj-database-url==1.0.0 Django==3.2.6 django-cors-headers==3.7.0 djangorestframework==3.12.4 durationpy==0.5 factory-boy==3.2.0 Faker==8.11.0 future==0.16.0 google-api-core==2.0.1 google-auth==2.0.2 google-cloud-language==2.2.2 google-cloud-vision==2.4.2 googleapis-common-protos==1.53.0 grpcio==1.39.0 gunicorn==20.1.0 hjson==3.0.2 idna==3.2 jmespath==0.10.0 joblib==1.0.1 kappa==0.6.0 packaging==21.0 pathspec==0.9.0 pep517==0.11.0 pip-tools==6.2.0 placebo==0.9.0 proto-plus==1.19.0 protobuf==3.17.3 psycopg2==2.9.5 psycopg2-binary==2.8.4 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.7.0 pycountry==20.7.3 PyJWT==1.7.1 pyparsing==2.4.7 pypiwin32==223 python-dateutil==2.8.2 python-http-client==3.3.2 python-slugify==5.0.2 pytz==2021.1 pywin32==305 PyYAML==5.4.1 regex==2021.8.28 requests==2.26.0 rsa==4.7.2 s3transfer==0.5.0 semantic-version==2.8.5 sendgrid==6.8.1 sentry-sdk==1.10.1 six==1.14.0 sqlparse==0.4.1 starkbank-ecdsa==1.1.1 termcolor==1.1.0 text-unidecode==1.3 toml==0.10.2 tomli==1.2.1 tqdm==4.62.0 troposphere==2.7.1 twilio==6.63.1 urllib3==1.26.12 wcwidth==0.1.9 Werkzeug==0.16.1 whitenoise==6.2.0 wsgi-request-logger==0.4.6 zappa==0.53.0 -
Integrating a Django project with FreeRADIUS and Coovachilli
How do I integrate a django project with FreeRADIUS and Coovachilli? I have looked for any documentation that can help, but I can only find PHP guides. I also have checked out OpenWisp, but it does not fit my requirements (too complex). So is there any guide on integrating a django project with FreeRadius and Coovachilli? -
can't open file 'manager.py': [Errno 2] No such file or directory
I'm trying to creat an aplication usign python and django, but this error keeps happening. What I've already tried: put python path and script in environment variables reinstall python reinstall django close and open vscode (I thought it was an update issue) run the server inside setup - the application folder If anyone can help me, very much. -
Django redirect /D/<anything> to /d/<anything>
I'm looking for a way to redirect any url that start with /D/ to the same URL with lowercased /d/. /D/<anything_including_url_params> to /d/<anything_including_url_params> I literally only want to redirect urls that start with /D/ - not /DABC/ etc... The suffix can also be empty, eg. /D/ > /d/ Is there a way to do that in Django? It is for a third-party app with urls included in projects urls. The alternative is to use re_path and change: path("d/", include(...)) to re_path(r"^[dD]/$", include(...)) but I'd rather do a redirect instead of this. -
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
I'm trying to deploy it on Railway. This error is coming. raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) Image of the error coming -
Django images not showing up in template
I've spent the whole day trying to find a solution for showing the images in the template but I couldn't find any solution to my case. This is my settings STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'DataCallGuide/static') ] My model class TroubleshootingSteps(models.Model): box_header = models.CharField(blank=True, null=True, max_length=250) box_content = models.CharField(blank=True, null=True, max_length=250) box_botton = models.CharField(blank=True, null=True, max_length=250) header = models.TextField(blank=True, null=True) sub_header = models.TextField(blank=True, null=True) text1 = models.TextField(blank=True, null=True) image1 = models.ImageField(blank=True, null=True, upload_to="images/") and the template {% extends 'base.html' %} {% load static %} {% block content %} <div class="container overflow-hidden"> <div class="text-center"> <h4 class="mt-5 mb-5">{{data.header}}</h4> </div> <h3 dir="rtl" class="rtlss">{{data.sub_header}}</h3> <img src="{{ data.image1.url }}"> </div> {% endblock%} Also when I click on the image link in admin pages it doesn't show the image and display page not found error with the below link http://127.0.0.1:8000/media/images/IMG-20220901-WA0009.jpg What is wrong please? -
Django IO bound performance drop with gunicorn + gevent
I have been working on an IO bound (only simple queries to database for getting info or updating it) application written in Django. As application is mostly db and redis queries, I decided to use gunicorn with async gevent worker class, but the weird part is that eventhough I'm running gunicorn with gevent (also monkey patched db for that purpose), I'm not seeing any performance gain by it, in fact, both requests/s and response time has dropped. Steps taken To do so, I have done the following: Installed greenlet, gevent & psycogreen as instructed in official docs. Patched postgres with psycogreen.gevent.patch_psycopg (tried wsgi.py, settings.py and post_fork in gunicorn) but to no avail. Tried running gevent's monkey.patch_all manually, also no use. This is my gunicorn.config.py: import gunicorn gunicorn.SERVER_SOFTWARE = "" gunicorn.SERVER = "" bind = "0.0.0.0:8000" worker_class = 'gevent' worker_connections = 1000 # Tested with different values keepalive = 2 # Tested with different values workers = 10 # Tested with different values loglevel = 'info' access_log_format = 'sport %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' def post_fork(server, worker): # also tried pre_fork and on_starting from psycogreen.gevent import patch_psycopg patch_psycopg() Result But the app only got slower, also note … -
django background longrunning tasks without celery
when writing the django-backend, we abandoned the use of Celery in favor of Process because we failed to cancel already running tasks but now we have to schedule long-runnning tasks that should be executed every 5 minutes or every 5 hours or every 3 hours (it's not necessary to be able to cancel them, of course, but I REALLY don't want to use celery) everywhere I saw that periodic tasks from celery were used to solve this problem, I want to find out what alternatives there are, it is important that it is performant and works on both windows and linux now we use such a code, we are satisfied with everything, except for a potentially bad performance # in tasks/management/commands/work class Command(BaseCommand): def handle(self, *args, **options): while(True): do_work() # work executed every 3 hours time.sleep(60 * 60 * 3) # sleep 3 hours # in tasks/management/commands/another_work class Command(BaseCommand): def handle(self, *args, **options): while(True): do_another_work() # work executed every 5 hours time.sleep(60 * 60 * 5) # sleep 5 hours how terrible is it to have several such tasks with while(True) + sleep in terms of performance? i wonder what code to solve this problem is at the heart of … -
Django - ForeignKey Filter Choices
I'd like to filter the choices that a user can choose in my ForeignKey Field. I basically have a ForeignKey for the subject of the Test and the actual topic of the Test. These topics come from a different model and are linked to a subject. Now I'd like to filter the choices to only include the topics that are linked to the currently selected subject. Is that possible and if so, how? models.py class Test(models.Model): student = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) thema = models.ForeignKey(Thema, on_delete=models.CASCADE, blank=True, null=True) school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, blank=True, null=True) grade = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(6)], blank=True, null=True) date = models.DateField(default=datetime.date.today) def save(self, *args, **kwargs): if not self.school_class and self.student: self.school_class = self.student.klasse return super().save(*args, **kwargs) class Thema(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) thema = models.CharField(max_length=50) -
Send a dict from js to views: return querydict who bursts my dict
I have a dict that I would like to send but I receive it in the form of a querydict whose content is no longer in the same form as the dict sent. How can i have an object that i can manipulate simply ? I would like to add the elements in a database so I should do a for loop and add by index (key1, key2) but I can't get the real length when i do len(request.POST) it return 5. .js function sendData(event){ const res = { 0:{"val1": 1, "val2":2}, 1:{"val1": 3, "val2":4}} ... $.ajax({ ... data: { "result": res, }, dataType: "json", ... }) } views.py def view1(request): print(request.POST) $ <QueryDict: {'csrfmiddlewaretoken': ['...'], 'result[0][val1]': ['1'], 'result[0][val2]': ['2'], 'result[1][val1]': ['3'], 'result[1][val2]': ['4']}> -
Set default values in Django form based on user's id/instance
I have created a customUser, then the foreign key of model class AddressBook (models.Model) is customUser.Id. Model Employer inherited from customUser. The other two models are class employee(CustomUser) and class Job(models.Model) Employer and Staff user could create a job. Now I would like to set fields of Employer and AddressBook in job form to be corresponding employer_org name and employer address if login user is employer. i.e. if employer 1 login, the job form will automatically show employer 1 org name and employer1 address. If employer 2 login, the fields will be employer2 org name and employer2 address. When Staff users sign in, they can select or type employer org name and employer address. Now my problem is even I sign in as employer 1, I can create a job for employer 2 when click the selection field. Here is my models: class AddressBook(models.Model): user=models.ForeignKey(get_user_model(),on_delete=models.CASCADE) street = models.CharField(max_length=64,blank=False) alt_line = models.CharField(max_length=64, blank=True) postcode= models.CharField(max_length=5, validators=[RegexValidator('^[0-9]{5}$', _('Invalid postal code'))], blank=False) city = models.CharField(max_length=64, blank=False) country = models.CharField(max_length=64, default="some name") class Meta: verbose_name = 'AddressBook' def __str__(self): return '{} {}, {}, {}'.format(self.street, self.alt_line, self.postcode, self.city) class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=250, blank=False) last_name = models.CharField(max_length=250, blank=False) email = models.EmailField(('email address'), unique=True) phone … -
How to access the value of a foreign key in a table in django?
I've 2 tables in a database on phpmyadmin that are connected by a foreign key. The table "bulle" contains the foreign key of the table "site". In enghlish : one "site" can contain some "bulles" (or not) and a "bulle" is always linked to a "site". class Bulles(models.Model): id_bulle = models.AutoField(primary_key=True) num_bulle = models.CharField(max_length=20) type_bulle = models.CharField(max_length=20) colories = models.CharField(max_length=20) latitude = models.FloatField() longitude = models.FloatField() date_vidange = models.DateField( db_column="date_vidange" ) id_depot = models.ForeignKey( "Depot", on_delete=models.CASCADE, db_column="id_depot" ) id_site = models.ForeignKey( "Site",related_name='bul', on_delete=models.CASCADE, db_column="Id_site" ) class Meta: db_table = "bulles" class Site(models.Model): id_site = models.AutoField( db_column="Id_site", primary_key=True ) nom = models.CharField( db_column="Nom", max_length=100 ) vitesse_b = models.FloatField(db_column="Vitesse_b") # Field name made lowercase. vitesse_c = models.FloatField(db_column="Vitesse_c") # Field name made lowercase. ecart_type_b = models.FloatField( db_column="Ecart_type_b" ) ecart_type_c = models.FloatField( db_column="Ecart_type_c" ) type_site = models.CharField( db_column="Type_site", max_length=20 ) longitude = models.FloatField(db_column="Longitude") latitude = models.FloatField(db_column="Latitude") Nombre_bulles = models.IntegerField(db_column="Nombre_bulles") date_vidange = models.DateField( db_column="Date_vidange") class Meta: db_table = "site" I've created a request to delete a row in "bulle" selected by the id_bulle (primary key). I'd like to get the "id_site" from this selected bulle that I delete in this request. Then, I need to count every "bulles" of the table that have this id_site. … -
Django formtools gets caught in a loop
I'm working on a multistep form using django-formtools lib, and I'm facing a flow problem. In a specific step (fotoFormulaMedica) I have two buttons where basically the user choose his pathway. Either "take photo" or "choose a file". If he choose to take photo, it'll take him to the step called foto and then, once he clicks in continue, it'll continue the rest of the steps. So the next step will be avisoDireccion. If he choose to "choose an image", it'll take stay in the current step, he'll select an image from his pc and then, once he clicks in continue will continue the rest of the steps. So the next step will be avisoDireccion. It works great!, however, when all the steps are filled, instead of take to the done.html, he goes back to fotoFormulaMedica and the user gets caught in a loop. This is the repo https://github.com/Alfareiza/logifarma-radicar-domicilio/tree/1.configurando-cargar-y-tomar-foto Also you can check here my : views.py https://github.com/Alfareiza/logifarma-radicar-domicilio/blob/1.configurando-cargar-y-tomar-foto/core/apps/base/views.py forms.py https://github.com/Alfareiza/logifarma-radicar-domicilio/blob/1.configurando-cargar-y-tomar-foto/core/apps/base/forms.py I'll appreciate your help. I've tried to make the flow not including one of the pathways. I mean, if I exclude the take photo feature or select file feature. The flow works as I expected. -
making form filters interact with each other django
So I have a page in django that have a couple of forms that work as content filters. self.fields["brand"] = forms.ChoiceField( label="Brand", choices=self.__get_brand_choice(), widget=forms.Select(attrs={"class": "form-select",'onchange': 'submit();'}), required=False, ) def __get_brand_choice(self): products_id = ( SalesView.objects.filter(business_unit=self.business_unit).values_list("brand", flat=True).distinct() ) products_brand = Brand.objects.filter( id__in=products_id ).values_list("id", "name").order_by("name") return [ (None, "TODAS"), *products_brand, ] this for example is the two parts of the brand filterb (but all of them are basicaly the same), I have other to related to product type and sales volume. At the moment, when I select one option on of them the others it filters the page content but it doesn't filter the options of the other so I can only choose valid options. That's what I want to change, I want them to interact. For example, if I want to filter bread on the page I also want the brand filter to only show brands that have bread, and if I choose I certain brand I want the product type filter to only show products type related to this brand. I know that basically i have to pass this other parameter(s) in the orm query that quet the product list, but am not sure how to get these parameters from the … -
I'm facing issues in sql fetch data in django ? It returns None
This is test.py from django.http import HttpResponse import mysql.connector MySQLdb = mysql.connector host = 'xxxxxx' username = 'xxxx' db = 'xxxx' port = '3306' password = 'xxxxxx' class sql: def __int__(self): pass def mysql_connection(self): try: mysql_conn = mysql.connector.connect(host=host, user=username, database=db, password=password, port=port, ssl_disabled=True) print("Connection Successfully Established...") return mysql_conn except Exception as e: print("mysql connection error".format(e)) exit(0) def update_approval(self, que): d = self.mysql_connection() cursor = d.cursor() cursor.execute(que) result = cursor.fetchone() return result This is my views.py from django.shortcuts import render, redirect from .forms import InputForm, TestForm from django.core.mail import send_mail from .test import sql import mysql.connector MySQLdb = mysql.connector def index(request): if request.method == "POST": form = InputForm(request.POST) # ids = form["git_Id"].value() # print(ids) # query = f'SELECT request_id FROM request_form_mymodel where git_Id={ids};' # # p = obj.update_approval(query) obj = sql() # git_id = 5666 ids = form.data["git_Id"] print(ids) # query = "SELECT request_id FROM request_form_db.request_form_mymodel where git_Id='%s'" % ids q = "SELECT request_id FROM request_form_db.request_form_mymodel where git_Id={}".format(ids) p = obj.update_approval(q) print(p) approve_url = f"http://my_url_path/test?request_id={p}" if form.is_valid(): send_mail( 'KSA Test Activation', approve_url, 'my_sender_email_id', ['receiver_id'], fail_silently=False, ) form.save() form = InputForm() else: form = InputForm() return render(request, 'home.html', {'form': form}) This is forms.py ` from django import forms from .models import MyModel, …