Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cannot read static files after deploying my project on pythonanywhere
I dont know if I did this right but during development phase I placed all my static files on my project's main directory, it looks like this: myproject myapp manage.py myproject - settings.py - urls.py ... static - css - somecssfile.css - js - somejsfile.js ... templates now my settings.py file looks like this: STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_URL = '/static/' after I deployed my project into pythonanywhere I added STATIC_ROOT: STATIC_ROOT = '/home/jeremiramos/cvs/staticfiles/' it does copy my static files to staticfiles folder when I do collectstatic on pythonanywhere console but it cannot read/load the static files I used on each and every page including admin page. and my staticfiles settings on pythonanywhere looks like this: I've tried checking the forums of pythonanywhere.com but it doesn't seem to help. Can anyone please explain what did I do wrong and what should I do? Thank you! -
Context processor ('AnonymousUser' object is not iterable)
In my context processor.py file I filter a table according to a user. This all works fine : def subject_renderer(request): return {"Calicount": Tools_Calibrated.objects.filter( user=request.user, calibrated=True, issued=True).count(), } The problem comes in when I log out and try log back in. Because there is no authenticated user at login I cannot call the query in the context processor. Question: Why is my context processor function being called when I am not calling the key in the login view template. I know how to solve this with templates but I was wondering how to solve it with context processors. Essentially omit it from one view. Thank you in advance -
Django Rest api - How to insert data from multiple tables into a single table
I have written a query where i'm just selecting different columns from multiple tables. I'm learning Django rest apis and i want to write an api where the data inside my query gets inserted into my custom dump table. Would really appreciate it if you could answer my question in brief. This is my query. query= """ select pa.height, pa.weight, pa.muac, pa.tsf, pa.bmi, pa.nutritionist_comment, pa.create_date_app_side, hp.gender, hp.name, hp.regn_date_hospital, hp.dob, hp.city, hp.diagnosis_list_id, hp.diagnosis_stage, hg.first_name, hg.phone_number, hg.preferred_language_id from patientcounselling_anthropometric as pa join hospital_patient as hp on hp.uuid=pa.patient_uuid join hospital_guardian hg on hg.patient_uuid=hp.uuid """ -
Django what to use instead of null?
I am doing return of investment calculation (ROI) and the formula is ((Net returns - Actual investment) / Actual investment ) * 100 For Ex: (( 2000 - 1000 ) / 1000 ) * 100 = 100% So in this, there is an problem: Initially the returns would be 0 until returns actually comes in ! By that, the above calculation shows -100% so i thought of using Null initally, so that if its null we can show 0% and when the value changes from null to something we can show respective ROI. The problem is, i cant perform addition on Null value, _investment = F('returns') + 2000 _investment .save() As the returns field is set to null F expression couldn't perform addition operation, so how to handle this ? As i cant set the default value as "0" and use if condition base on it - because there may be some negative returns also. Please suggest some way to tackle this ! -
AJAX function is called twice
I'm building an app with Django and AJAX, and I'm having trouble with AJAX, because every time a view is called, it's done twice. For example, I have a DataTable in which I display a data series, and this DataTable is constructed after making an AJAX call to the view in Django, and this is executed twice ... I put the code below: analysis.js: function analysis_attributes_list() { $.ajax({ url: "/analysis/analysis_attributes_list", type: "GET", dataType: "json", success: function (response) { if ($.fn.DataTable.isDataTable('#top_chart')) { $('#top_chart').DataTable().destroy(); } $('#top_chart tbody').html(""); for (let i = 0; i < response["top_chart"].length; i++) { let row = '<tr>'; for (let j = 0; j < response["top_chart"][i].length; j++) { if (j !== 5) { if (response["top_chart"][i][j] === true) { row += '<td>' + '<input class="form-check-input" type="checkbox" value="" onchange="analysis_attributes_list_checkbox_handler(this)" checked>' + '</td>'; } else if (response["top_chart"][i][j] === false) { row += '<td>' + '<input class="form-check-input" type="checkbox" value="" onchange="analysis_attributes_list_checkbox_handler(this)">' + '</td>'; } else { row += '<td>' + response["top_chart"][i][j] + '</td>'; } } } row += '</tr>'; $('#top_chart tbody').append(row); } $('#top_chart').DataTable({ "pageLength": 5, "lengthMenu": [[5, 10, 20, -1], [5, 10, 20, 'All']], "destroy": true, "select": true, "responsive": true, }); }, error: function (error) { console.log(error); } }); $(document).ready(function () { analysis_attributes_list(); }); … -
Find STL File Weight Using Python Django
I want to make website with django. I want to calculate Stl File weight with infill density. User upload STL file and enter infill density on website than i want to calculate STL file weight like cura or any slicer application. How can i calculate it. I don't find any library. Thanks -
Change the name of the "Add" button in Django Admin
As we known, there is an "Add" button in each model in django admin site. How can I change the name of it into like "Add Student" to make it customerized. -
How to SEND user interaction data to database in Django
I am using a JavaScript script which when embedded into HTML will store user interaction with website, for example if website is an e-commerce site - then script will collect links, buttons clicked by user such as buy, sell, my orders, Wishlist etc. You can view the live interaction here :- https://sauravfouzdar.github.io/Web-Tracker/ Github repo link with Js script :- https://github.com/sauravfouzdar/Web-Tracker Now I want store these collected objects into a database using Django. This is where I need help // Gather Additional Data and Send Interaction(s) to Server __sendInteractions__: function () { var interactor = this, // Initialize Cross Header Request xhr = new XMLHttpRequest(); // Close Session interactor.__closeSession__(); // Post Session Data Serialized as JSON xhr.open('POST', interactor.endpoint, interactor.async); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.send(JSON.stringify(interactor.session)); return interactor; } -
Creating a Python options console that's widely accessible
I've been making a program that uses specific settings from a settings file. This has been my first programming project, and I've been using it as an excuse to learn more in-depth stuff in Python. The settings used by the program are primarily bools indicating what the main program should and shouldn't pay attention to when operating. The first iteration of the program used a config.py file within the environment to simply import config. This didn't work so well as I had to keep editing this specific file, which as it got longer with more settings became harder to maintain. I recently learned to use Tkinter to make a separate config application where I could simply use checkboxes to set the bools. I've been using that since, but there's still one issue with it: Accessibility. The program runs on a Raspberry Pi which I don't normally use and just runs as a server. The main program gets called from a cronjob at 4 AM each day, which loads the settings from a JSON file created by the aforementioned settings GUI. As it stands, I need to use Teamviewer to actually use this GUI so while I'm proud of what I've … -
How to dumpdata in django inside the code [duplicate]
I know you could dump your data with following command in terminal: python manage.py dumpdata auth.user --pk 3 now assume I want to dumpdata inside my code not in terminal. Because I need the result jsons coming from dumpdata command. How can I do that? -
Field 'id' expected a number but got <taggit.managers._TaggableManager object
I am building a BlogApp i am stuck on an Error. What i am trying to do :- I am filtering users with similar tags. BUT when i try to filter then the error is keep showing - Field 'id' expected a number but got <taggit.managers._TaggableManager object at 0x0000015B266D3288>. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) interests = TaggableManager(verbose_name='interests') views.py def test_hobbiesss(request,user_id): users = Profile.objects.filter(interests=request.user.profile.interests) context = {'users':users} return render(request, 'mains/test_hobbiesss.html', context) What have i tried :- I also tried by users = Profile.objects.filter(interests=request.user.profile.interests.all()) BUT it shows this error The QuerySet value for an exact lookup must be limited to one result using slicing. Any help would be much Appreciated. Thank You in Advance. -
Celery Crontab in not Picking the tasks
I have added crontab for every 1 minute in the celery beat schedule. Migrations also done properly. can I miss anything in this code ?Is the crontab format will be correct. Thanks in advance . the crontab for minutes will work settings.py INSTALLED_APPS = [ 'app1', 'django_celery_beat', ] CELERY_BROKER_URL = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task-second': { 'task': 'app1.tasks.elast', 'schedule': crontab(minute=1), } } celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() __init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) tasks.py from __future__ import absolute_import, unicode_literals from proj.celery import app @app.task def elast(): print("start") return "Exceuting after 1 minute" celery beat worker: celery -A proj beat --loglevel=debug --scheduler django_celery_beat.schedulers:DatabaseScheduler logformat : celery beat v5.1.2 (sun-harmonics) is starting. [2021-07-27 11:07:00,894: DEBUG/MainProcess] beat: Ticking with max interval->5.00 seconds [2021-07-27 11:07:00,916: DEBUG/MainProcess] beat: Waking up in 5.00 seconds. [2021-07-27 11:07:05,931: DEBUG/MainProcess] beat: Synchronizing schedule... [2021-07-27 11:07:05,932: DEBUG/MainProcess] Writing entries... -
Django - using a queryset to determine which choices to use for a field
With my app, a user chooses a few settings and these are saved as a GradeBookSetup object. One of the settings is a list of tuples for a choice. I have a form for Grade objects, and grade.score is determined from choices. The choices used come from the above mentioned GradeBookSetup object. I would like the form to use a list of choices based on the GradeBookSetup setting. In the code below you will see in the view that this setting is determined with gradescale = GradeBookSetup.objects.get(user=request.user) and the field gradescale.scale_mode can be passed to the form. I originally thought I could do the above query in the form, but I then learned this is not possible. So I think I am passing this gradescale.scale_mode to the __init__ method in the form, but I don't know how/if I can get this into my if / elif statements in the form. views.py def addsinglegrade(request, classroom_id, student_id): c = Classroom.objects.get(id=classroom_id) s = Student.objects.get(id=student_id) course = Course.objects.get(classroom=classroom_id) gradescale = GradeBookSetup.objects.get(user=request.user) objective_list = Objective.objects.all().filter(course=course) objective_tuple = [(o.id, o.objective_name) for o in objective_list] form = SingleGradeForm(objs=objective_tuple, gradescale=gradescale.scale_mode) context = {'student': s} context['classroom'] = c context['form'] = form if request.method == 'POST': ....... forms.py class SingleGradeForm(forms.Form): … -
DRF Get All Fields of OneToOne Model
I'm relatively new to DRF and currently stuck at an issue. After lot of trials I tried looking around but couldn't find something what I want. In case this question has already been answered please do direct me to the original question. Thanks in advance for the help! Problem: I've a profile model that has one to one relation with User model. When I create a new user object the profile object is auto created as expected. I would like to create an API such that when I execute it like api/profile/ in addition to returning the profile model fields it should also return all the fields from User model i.e. first_name, last_name, username, email etc... class Profile(models.Model): rater = models.OneToOneField(User, on_delete=models.CASCADE, related_name='approval') certified = models.ManyToManyField(Protocol, blank=True, default=None, related_name='trained') is_approved = models.BooleanField(default=False) My ProfileSerializer is as follows: class ProfileSerializer(serializers.ModelSerializer): approval = UserSerializer(read_only=True) class Meta: model = Profile fields = '__all__' When I run the API I get the following response: [ { "id": 1, "rater": 3, "certified": [], "is_approved": false } ] How can I get the following response: [ { "id": 1, "rater": 3, "certified": [], "is_approved": false, "first_name": xyz, "last_name": abc, "username": 123, "email": abc@gmail.com, } ] -
How Can I attach a web based cloud server to django website? Which is the best cloud database? [closed]
How Can I attach a web based cloud server to django website? Which could be the best cloud database? I run my web on google cloud and I want to attach a cloud database to it. But How?? -
Django filter based on ForeignKey model field
I am trying to eliminate a field of the Barcode model that is redundant. mostrecentscantime of Barcode is not needed because I can reference mostrecentscan.time. class Scan(models.Model): time=DateTimeField(default=timezone.now) barcode=ForeignKey('Barcode',on_delete=models.CASCADE,related_name='scans') location=ForeignKey(Location,on_delete=models.CASCADE) class Barcode(models.Model): barcode = CharField(max_length=50,unique=True) time_created = DateTimeField(default=timezone.now) mostrecentscan=ForeignKey(Scan,on_delete=models.CASCADE,related_name='+',null=True) mostrecentscantime=DateTimeField() The problem with eliminating mostrecentscantime arises with this query where I am trying to determine all Barcode objects where the time_created and the time of the mostrecentscan is greater than 7 days. Working Query: barcodematches = Barcode.objects.annotate( diff=ExpressionWrapper(F('mostrecentscantime') - F('time_created'), output_field=DurationField()) ).filter(diff__gte=timedelta(days=7)) I cannot simply reference mostrecentscan.time in this context. I have also tried adding an @property field to Barcode which doesn't work either. -
How to know the user is sign-in or not drf-social-oauth2 and reactjs
I set user login system with react-google-login and drf-social-oauth2 At first I post the message like this and check the user is signed in or not. http://localhost:8008/auth/convert-token Then how can I get to see if user is login or not in ReacJS?? I want to show welcome your@mail.com if user log-in class TestPage extends React.Component { render(){ return ( <React.Fragment> <GoogleLogin clientId={googleClientId} isSignedIn={true} buttonText="LOGIN WITH GOOGLE" onSuccess={(response) => handleGoogleLogin(response)} render={(renderProps) => ( <button onClick={renderProps.onClick} disabled={renderProps.disabled} type="button" class="login-with-google-btn" > Sign in with Google </button> )} onFailure={(err) => console.log("Google Login failed", err)} /> <GoogleLogout clientId={googleClientId} buttonText="Logout" onLogoutSuccess={logout} > </GoogleLogout> </React.Fragment> ); } -
Ldap search for extended attributes in python
When running an ldapsearch against active directory, to get the "extended attributes" of an object, we use the "+" operator. For example, ldapsearch -h localhost -p 1389 -D "cn=Directory Manager" \ -w password -b "dc=example,dc=com" "(objectclass=*)" "+" Can someone help me on how I can do the same query(getting the extended attributes) using python code. I am using ldap3 package on my current python code. -
how I add sidebar multi from in django
when I run HTML file look like enter image description here but when I using the Django framework that time it will show enter image description here please tell me what is the problem? and how to solve the problem. -
How to Integrate Web API into a ReactJS Application
I currently have a web application using ReactJS for the front-end, Django for the back-end and MariaDB for the database. Recently, I obtained a SecuGen Hamster Plus fingerprint scanner and I wish to use it for authentication in my web application. I downloaded the Web API code from the SecuGen website and managed to get it running on my localhost. However, I have no idea how to integrate the Web API with my web application so that I can use the fingerprint data for authentication. Could someone help me? -
django: VSCode not recognizing request.POST.get
And in your views.py you can get the use input using the POST method usergivenip = request.POST.get('textfield', None) i did this in my code and i got this error: "module 'django.http.request' has no attribute 'POST'. does this module not exist anymore or did it change? do i need to import something? (other than django.http.request) -
show similar users which's interest tags is similar to other users
I am using Django 3.2 and I am newbie in Django. I am building a similarity app. Like if someone's interest tags (using Tag Field) is similar to other users then show other user in the explore users list. I build a Tag Field which contains interests tags. like :- walking,etc. For Example - user_1 set to "walking, travelling". AND user_2 set to "walking", Then user_2 will be in explore users list of user_1. I am using django taggit field. BUT When i try to show similar users then similar users are not showing. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) email = models.EmailField(max_length=60,default='') interests = models.CharField(max_length=2000,default='') views.py def users_list(request,user_id): tags = Tag.objects.filter(profile__interests=user_id).distinct() users = Profile.objects.filter(interests__in=tags).distinct() context = {'users': users} return render(request, 'users_list.html', context) In view i am accessing Tag Model and I am getting all the profiles which are similar in request.user interests tags. BUT the users are not showing. I will really appreciate your Help. Thank You. -
Missing module source
I am a beginner in python, django coding. I just receive a folder that consist of a web made out of django. After i recieve it, I use powershell and go to that folder : pipenv shell pipenv install Django==3.2.5 When i open the codes in visual studio code, I got problems: How do i solve this issue? -
/auth/convert-token requires username in create_user
I have custom user model and my user manager is like this below class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) in settings.py ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'none' It doesn't require username use email instead. Now I try to set Django rest framework to use oauth (google login) My first test is post the token here to register a user http://localhost:8008/auth/convert-token However there comes error. TypeError at /auth/convert-token create_user() missing 1 required positional argument: 'username' My … -
Django, creating custom order/filter based on value from another Model
I am creating a Reddit clone and currently trying to implement the posts sort functionality. I am stuck on sorting the posts by "most upvotes." I believe I structured my models/database incorrectly and hoping I won't have to redo it because I have my voting system working perfectly. // models.py class Post(models.Model): title = models.CharField(max_length=300) content = models.TextField() date_created = models.DateTimeField(verbose_name="date_created", auto_now_add=True) date_edited = models.DateTimeField(verbose_name="date_edited", auto_now=True) author = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=["title", "subreddit"], name="sameTitle_in_sameSubreddit_notAllowed") ] def __str__(self): return self.title class Vote(models.Model): original_post = models.ForeignKey(Post, related_name="post_votes", on_delete=models.CASCADE, null=True) original_comment = models.ForeignKey(Comment, related_name="comment_votes", on_delete=models.CASCADE, null=True) owner = models.ForeignKey(User, related_name="votes", on_delete=models.CASCADE) vote_choice = models.IntegerField(choices=((1, "UP"), (2, "DOWN"))) class Meta: constraints = [ models.UniqueConstraint(fields=["original_post", "owner"], name="sameOwner_samePost_notAllowed"), models.UniqueConstraint(fields=["original_comment", "owner"], name="sameOwner_sameComment_notAllowed") ] Looking at the "Votes" model, I was able to write a raw SQL query in a view (testing purposes) that sorts the 'original_post' column by the most upvotes and returns it in a list. Is it possible to take the results of this query and apply a custom sorting to the "Post" queryset. So, for example, sort the Posts by 'post_id' but sort the iDs in the same order of the 'most upvotes list.' // …