Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter django queryset by regex for a phone number in any format?
Users in my postgresql database have field that stores phone numbers in different formats, like: 34567889 +34567889 +(345)67889 or even +(345) 678 89 Having the string with only digits (34567889) I want to be able to find a record no matter of format. I am trying to use regex search for this (with no luck), that looks like this: queryset.filter(phone__regex=r"^.*?3.*?4.*?5.*?6.*?7.*?8.*?8.*?9$") Same regex works for me outside the django orm, in interpreter, for instance, but does not work when I do queryset filter. Any ideas what I am doing wrong? Any help will be appreciated. Thanks in advance. -
Python Django script throwing an error -HTTPConnectionPool Max retries exceeded
I have Django App and I am trying to get data from our server. The code is as below: def login(request): #global userlist, login_data if request.method == "POST": # get email or mobile_number and password from login.html screen email_id = request.POST.get("your_name") password = request.POST.get("your_pass") try: login_data = requests.get('http://<our URL>/api/usersapi/?mobile_number=' + email_id + '&password=' + password, timeout=0.05).json() # get user api json data if len(login_data) == 1: # check dictionary of login_data is empty or not for x in login_data: user_type = x['user_type'] user_id = x['user_id'] request.session['login_data'] = user_id request.session["admin_status"] = True return render(request, 'gui/dashboard.html', {'user_type': user_type, 'login_data': login_data}) else: # if correct details then return to dashboard page return render(request, 'gui/login.html', {'msg': 'Wrong Username and Password'}) except requests.exceptions.ConnectionError as e: print(e) r = "No response" return render(request, 'gui/login.html', {'msg': e}) return render(request, 'gui/login.html') It throws an error while establishing the connection. HTTPConnectionPool Max retries exceeded with (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f3b389becc0>: Failed to establish a new connection: [Errno 111] Connection refused', I have already seen and applied many solutions related to the same error. But, I am not able to figure out the problem. Our system ulimit-> 65536 I have configured settings using WSGI. and /etc/hosts has our url … -
Creating a notification system in Django
so I am building the backend for a web forum using Django & Django REST Framework and would like to include a notification system. So I have a "Discussion" Model: def user_directory_path(instance, filename): return f'{instance.id}/{filename}' class Discussion(models.Model): title = models.CharField(max_length=250) content = models.TextField(max_length=10000) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_pinned = models.BooleanField(default=False) is_open = models.BooleanField(default=True) is_boosted = models.BooleanField(default=False) started_by = models.ForeignKey(to=User, related_name='started_discussions', on_delete=models.CASCADE) subscribers = models.ManyToManyField(to=User, related_name='subscribed_discussions') tools = models.ManyToManyField(to=Tool, related_name='belongs_to_channels', blank=True) channels = models.ManyToManyField(to=Channel, related_name='discussions') def __str__(self): return f'{self.id} | By: {self.started_by.username} | Content: {self.title} ...' and I have a "Comment" Model: class Comment(models.Model): content = models.CharField(max_length=5000) discussion = models.ForeignKey(to=Discussion, related_name='comments', on_delete=models.CASCADE) written_by = models.ForeignKey(to=User, related_name='written_comments', on_delete=models.CASCADE) liked_by = models.ManyToManyField(to=User, related_name='liked_comments', blank=True) def __str__(self): return f'{self.id} | By: {self.written_by.username} | {self.content[0:30]} ...' Basically my question is that I would like to create a functionality where if someone creates a new comment on a discussion, the users that have subscribed to this discussion will get a notification. So for example if someone comments on a discussion you are subscribed to, you'll get a notification "New Comment from {user that commented} on {discussion you're subscribed to}" My thought was to create a new django app "Notification" with the respective model and … -
'NoneType' object has no attribute 'append'..why is this the case since i did not assign that statement to another variable
AttributeError 'NoneType' object has no attribute 'append' def func(request): if request.method == 'POST': html = request.POST.get('html') email = request.POST.get('email') first_html = BeautifulSoup(html, features='html.parser') second_html = BeautifulSoup(''.join(open('file1.html'))) for element in second_html: first_html.body.append(copy.copy(element)) I am trying to concatenate 2 html using Beautiful Soup, However i receive an error in the line: first_html.body.append(copy.copy(element)) why is this the case since i did not assign that statement to another variable -
How do I make Django form fields only editable if they're blank?
The use case: It's kind of like a signup sheet. The form has 3 fields, each of which should only be editable if they were blank when the form was requested. Once the form is submitted, these fields for this specific instance of the model shouldn't be editable. The question: How do I do this? I was thinking of using Javascript to set the fields to editable if they already have something in there, but I'm almost certain there's an easier way. -
Wagtail Admin Filter Button
I'm asking 'cause I haven't found such information in docs. I've read than construct_explorer_page_queryset hook allows to filter queryset. But it does on a constant basis. Is it possible to create button to turn on/off this filter. For example, I have Blog Page (parent page), than includes Posts, Tags, Categories Pages (children). And Blog Page listing shows me all types of these pages. I want to filter them by buttons Only Categories, Only Tags, Only Posts. Sure, I know than there is ModelAdmin feature. But it doesn't fit my requirements due to some issues with localize. I have to use only Page Explorer. If I just read heedlessly and this information can be found in docs - please, point me. Thanks! -
Why is there a difference in the output of pythonanywhere and local visual studio code?
I am trying to make a speech to text program in python and deploying it with django . On the same audio file I am getting different results when I try to run it on pythonanywhere and visual studio code Here is my code : import speech_recognition as sr def aud(): f = 'filepath/output.wav' r = sr.Recognizer() x = sr.AudioFile(f) with x as source: audio = r.record(source) mytext= r.recognize_google(audio) return(mytext.lower()) VSC Output: "ok around better late than never ad-hoc" Pythonanywhere Output: "oakwood aren't naturally at home" How can I get the same result ? -
understanding transaction_db fixture in pytest-django
Python 3.7 Django 3.1 PostgreSQL 12.6 I'm fairly new to unit tests, especially in django. I'm using pytest along with pytest-django to manage my tests. I came across a global fixture in pytest-django called transactional_db. My understanding, so far, is that if you want transactions to be rolled back, if something goes wrong during tests run, then use transactional_db. Also, Doc says This fixture can be used to request access to the database including transaction support. This is only required for fixtures which need database access themselves. A test function should normally use the pytest.mark.django_db() mark with transaction=True to signal it needs the database. Blockquote I'm also using factory to create ModelFactory to be used in unittests. something like below- class MyModelFactory(factory.django.DjangoModelFactory): title = factory.LazyAttribute(lambda x: faker.name()) class Meta: model = MyModel As I mentioned above, doc says “This is only required for fixtures which need database access themselves”. but if I understand correctly, the Modelfactory also accesses the Database. I mean Modelfactory create/update objects in the DB. isn’t it true? This is what confuses me, what is the definition of access to the database? What's the use of transactional_db in pytest? In My case, I have a simple REST … -
Updating all instances of a model everyday in Django
First of all, I know this is not a general "stackoverflow" type of question, but I can't find another good website to ask this. I personally think this is a perfectly reasonable question, so I hope you can help me out here. Basically how can you make all the model instances updated on a daily basis in Django? Right now, I have a model that has each of my students' information. I want to update each of my students information everyday, so that the correct students will show up in my schedule list in django daily. For example, if it is a holiday, then a "show in my list" field in each student's model will be updated to false. Of course, I am going to add a lot of functions such as "is it a holiday today?", "does the student have a class with me today?", "at what time does the student have class with me today?", etc. If the student matches all of the requirements(or functions) to "show up" in my schedule, then the "show in my list" field in each student's model will be updated to true. My schedule list will then loop through all of my students … -
key "article" which have some long string value right? So I want you to divide it into parts
http://139.59.86.56/coursesetup/api/4 Do you see keys and values? So there is a key "article" which have some long string value right? So I want you to divide it into parts. For example: "key1": "This is the first line" "Key2": "This is the second line" Not only two, as many lines as it has and before that give me a number of parts like "no_of_parts": "5" This means it contains 5 lines or 5 parts. How can I do this? Thanks -
Unable to translate
I am using Django and angular and in my template I have that : <table class="table"> <thead> <th>{% trans 'Name' %}</th> </thead> <tbody> <tr ng-repeat="word in allwords"> <td>{% trans word.name %}</td> </tr> </tbody> </table> This line is translated perfectly <th>{% trans 'Name' %}</th> But that line is not translated at all : <td>{% trans word.name %}</td> I precise I tried blocktrans also but without effects. Of course I did the compilemessages to test that. Could you help me please ? Thank you very much ! -
leaves matching query does not exist [closed]
leaves = Leaves.objects.get(user=user,leave_type=leave_type) balance = leaves.balance print(expanded, days) emp = Employee.objects.get(user=user) m_eid = emp.team.manager_eid manager = Employee.objects.get(eid=m_eid) email = manager.user -
How to reset a password with the implemention of the forms in django?
Here, I'm creating a custom password reset page with custom form in Django. Also, I use django-rest-resetpassword package to generate reset tokens and send it via mail. Once the user clicks the link it verify the token for expiration, used-ones and if the tokens are good so the user can change the password. say the url is reset-password/verify-token/?token=123tq24uig32h it redirects to reset-password/verified/ reset-password/verified/ This page shows the template(i.e.,HTML page) for new password and confirm password. When the tokens are good it is redirected to a template. So, There may arise a question that if the user already changed the password when he knows the url user can visit this page reset-password/verified/ to prevent is I also passed token to verified page using get method and verify the status of the token. Now I need to validate the form-template of new password and confirm password The code for token verificaiton is here class CustomPasswordTokenVerificationView(APIView): """ An Api View which provides a method to verifiy that a given pw-reset token is valid before actually confirming the reset. """ throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = CustomTokenSerializer def get(self, request, *args, **kwargs): toks = … -
How do I get multiple rows from django database? [duplicate]
Hello I am trying to create an employee attendance program and I want to make it so that the employees can see the total hours they worked. This is the code that creating the problem: elif 'checkName' in response.POST: if form.is_valid(): n = form.cleaned_data["name"] t = Name.objects.filter(name=n) totalHours = datetime.combine(t.date, t.timeOut) - datetime.combine(t.date, t.timeIn) messages.success(response, totalHours) return redirect('/') The error I get is 'QuerySet' object has no attribute 'date' and if I use t = Name.objects.get(name=n) it shows an error that says 'get() returned more than one Name -- it returned 2!' -
Django Query data optimization
Recently, I watched Django and discovered the teaching videos of select_related and prefetch_related. So I installed debug_toolbar and took a look at my website I searched the database too many times on one page. I must convert it to json and send it back to the front end Can I still optimize? Is this the only way to go? Below is my model . models.py def get_upload_path(instance, filename): return f'register/{instance.owner.job_number}/{filename}' def image_upload_path(instance, filename): date = datetime.datetime.strptime(instance.date, '%Y-%m-%d %H:%M:%S') return f'image/{date.year}/{date.month}/{date.day}/{filename}' class UserProfile(models.Model): name = models.CharField(max_length=64) department = models.CharField(max_length=32) job_number = models.CharField(max_length=32, unique=True) card_number = models.CharField(max_length=32, unique=True) location = models.CharField(max_length=32) date = models.DateTimeField() class UserRegister(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) date = models.DateTimeField() feature = ArrayField(models.FloatField(null=True, blank=True), null=True, blank=True, size=512) image = models.ImageField(upload_to=get_upload_path) class Meta: db_table = 'UserRegister' class UserImage(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) heat = models.CharField(max_length=8, blank=True, null=True) date = models.DateTimeField() image = models.ImageField(upload_to=image_upload_path) punch_in = models.CharField(max_length=8, blank=True, null=True) class Meta: db_table = 'UserImage' views.py def get_db_data(db, page, limit, model): data = [] paginator = Paginator(db, limit) try: page_object = paginator.page(page) all_page = paginator.num_pages for db_data in page_object: images = [] for image in db_data.userregister_set.all(): try: url = f'/static/uploads{image.image.url}' except ValueError: url = '/static/imgs/assets/none.jpg' images.append({'id': image.id, 'url': url}) _ = { … -
Django 'attempt to write a readonly database' even if db file has read and write permissions
I am using SQLite3, Ubuntu server. I have checked the read and write permissions of the database file. It is: -rw-r--r-- Doesn't this mean that the file has read and write access? So why is Django error saying attempt to write a readonly database? Thanks in advance! -
Load Datatable after passing parameter on form submit to Django View
Unable to pass parameters at view side from the template and based on that want to load Datatable in my Django project I have a simple form created in a template dateForm.html with date fields <form method="POST"> <div class="row justify-content-center"> <div class="col-md-auto"> Start Date: <input type="text" name="startDate" id="startDate"> </div> <div class="col-md-auto"> End Date: <input type="text" name="endDate" id="endDate"> </div> <div class="col-md-auto"> <button name="search" value="search" type="submit">Search</button> </div> </div> </form> On Form submit want to pass the selected date to studentView.py Issue: This form is inside a different python app 'admin' and Datatable Url is redirecting to a different python app 'student' View. So, Confused about how can I get this submitted date to the view the same as my Datatable view(Datatable is inside the dateForm.html only and dateForm.html is rendering from Adminview.py) -
how to fix error Koa Native Open edX platform Ubuntu 20.04 64 bit Installation error?
i am installing Koa Native Open edX platform Ubuntu 20.04 64 bit through followed by https://openedx.atlassian.net/ documentation but last moment i getting this error how to fix it error: 7184 bytes of body are still expected fetch-pack: unexpected disconnect while reading sideband packet fatal: early EOF fatal: index-pack failed bash: line 155: cd: configuration: No such file or directory fatal: not a git repository (or any of the parent directories): .git fatal: not a git repository (or any of the parent directories): .git bash: line 162: cd: /var/tmp/configuration: No such file or directory ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' bash: line 168: cd: /var/tmp/configuration/playbooks: No such file or directory ============================================================ Ansible failed! ------------------------------------------------------------ Decoded error: python3: can't open file '/var/tmp/configuration/util/ansible_msg.py': [Errno 2] No such file or directory ============================================================ Installation failed! -
Django: OperationalError at /api/v1/ no such table: leads_followup
models.py class Followup(models.Model): FOLLOWUP_CHOICES = ( (0, 'Not Finished'), (1, 'Finished') ) lead = models.ForeignKey( Lead, on_delete=models.CASCADE, related_name='followups' ) response = models.CharField( max_length=150, blank=True, null=True ) response_number = models.SmallIntegerField( 'Number of given followup response (eg. 1)', default=1 ) date = models.DateField(auto_now_add=True) action = models.SmallIntegerField( choices=FOLLOWUP_CHOICES, default=FOLLOWUP_CHOICES[0][0] # not finished item's index. ) recorded_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='recorded_followups' ) def __str__(self): return self.lead.name I have run all migrations locally. Whenever I make some change in my model and I try to run migrations, django complains about this error. There's another case, when I mention this model in the loop of the viewset, Django will raise this exception. views.py class FollowupViewSet(viewsets.ModelViewSet): # I comment from here followups = Followup.objects.all() expected_followup_ids = [] lead_names = [] for followup in followups: if followup.lead.name not in lead_names: lead_names.append(followup.lead.name) expected_followup_ids.append( Followup.objects.filter(lead=followup.lead).last().id ) else: continue queryset = Followup.objects.filter(id__in=expected_followup_ids) # to here serializer_class = FollowupSerializer filter_backends = [DjangoFilterBackend, ] filterset_fields = ['date', 'recorded_by', 'response'] What's wrong here? How can I run migrations without having caused the error and without commenting on my views.py file's code block? -
You must set settings.ALLOWED_HOSTS if DEBUG is False. Django-r-f
I want to prepare the server for deployment and this is the setup. settings.py is split into dev.py and prod.py in settings.py at the bottom ALLOWED_HOSTS = [] I also have tried ALLOWED_HOSTS = ['*'] dev.py from ..settings.settings import * DEBUG = True wsgy.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'movie_api.settings.dev') CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. When I import settings in the manage.py shell, the settings.DEBUG = False .. why? How to make wsgi.py read the correct file? -
Dependencies are not being installed Elastic Beansalk + Django
I am currently running Django 3.1.2 and Python 3.7 running on 64bit Amazon Linux 2 From the elastic beanstalk logs its telling me that there is no django module. 2021-04-08 05:09:30,592 P3788 [INFO] ============================================================ 2021-04-08 05:09:30,593 P3788 [INFO] Test for Command 01_migrate 2021-04-08 05:09:30,596 P3788 [INFO] Completed successfully. 2021-04-08 05:09:30,596 P3788 [INFO] ============================================================ 2021-04-08 05:09:30,596 P3788 [INFO] Command 01_migrate 2021-04-08 05:09:30,622 P3788 [INFO] -----------------------Command Output----------------------- 2021-04-08 05:09:30,623 P3788 [INFO] Traceback (most recent call last): 2021-04-08 05:09:30,623 P3788 [INFO] File "manage.py", line 11, in main 2021-04-08 05:09:30,623 P3788 [INFO] from django.core.management import execute_from_command_line 2021-04-08 05:09:30,623 P3788 [INFO] ModuleNotFoundError: No module named 'django' 2021-04-08 05:09:30,623 P3788 [INFO] 2021-04-08 05:09:30,623 P3788 [INFO] The above exception was the direct cause of the following exception: 2021-04-08 05:09:30,623 P3788 [INFO] 2021-04-08 05:09:30,623 P3788 [INFO] Traceback (most recent call last): 2021-04-08 05:09:30,623 P3788 [INFO] File "manage.py", line 22, in <module> 2021-04-08 05:09:30,623 P3788 [INFO] main() 2021-04-08 05:09:30,623 P3788 [INFO] File "manage.py", line 17, in main 2021-04-08 05:09:30,623 P3788 [INFO] ) from exc 2021-04-08 05:09:30,623 P3788 [INFO] ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? 2021-04-08 05:09:30,623 P3788 [INFO] ------------------------------------------------------------ I have … -
Transferring data between Django projects
I have two Django projects with similar apps, and I need to transfer/transform data from one app (@djangoproject1) to another (@djangoproject2). My script to access both projects/databases (inspired by this post) looks like this import os import sys from django.apps import apps sys.path.append('/django/djangoproject1') sys.path.append('/django/djangoproject2') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproject1.settings") from djangoproject1 import settings apps.populate(settings.INSTALLED_APPS) from app1.models import Page mypage = Page.objects.get(id=1234) print(mypage.title) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproject2.settings") from djangoproject2 import settings apps.populate(settings.INSTALLED_APPS) from app2.models import Page mypage = Page.objects.get(id=3421) print(mypage.title) It fails importing the model Page from app2, referring to the first model in models.py: RuntimeError: Model class app2.models.FirstModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. If the configuration for one project (either djangoproject1 or djangoproject2) is commented out, the script works fine (printing the respective page's title). How can I load the database content from one project/app, then switch to the other project/app properly? -
Django Fetch Data from multiple models connected using Foreign Keys
I am new to Django and currently working on my first project. I have my models designed liked this: class BasketProductMapping(models.Model): product_reference = models.ForeignKey(Product, default=1, null=True, blank=True, on_delete=models.CASCADE) mapped_basket_name = models.CharField(max_length=5,null=False, blank=False) mapped_product_name = models.CharField(max_length=30, null=False, blank=False) def __str__(self): return self.mapped_basket_name class ShelfBasketMapping(models.Model): mapped_basket_name_reference= models.ForeignKey(BasketProductMapping, on_delete=models.CASCADE, default=1) mapped_name_shelf = models.CharField(max_length=15, null=False, blank=False, default='default') mapped_name_basket = models.CharField(max_length=15, blank=False, null=False, default="default") def __str__(self): return self.mapped_name_shelf class KioskShelfMapping(models.Model): mapped_shelf_basket_name_reference = models.ForeignKey(ShelfBasketMapping, on_delete=models.CASCADE, default=1) mapped_shelf_name = models.CharField(max_length=15, null=False, blank=False, default="default") mapped_kiosk_name = models.CharField(max_length=15, blank=False, null=False, default="default") def __str__(self): return self.mapped_shelf_name Say for my first model I have my Data like this: B1 - P1 B1 - P2 B2 - P1 B3 - P1 and for my second models I have my data like this: S1 - B1 S2 - B2 S1 - B3 and finally for my third model, I have my data like this: K1 - S1 K2 - S2 Here is my serializers.py: class KioskShelfMappingGetSerializer(serializers.ModelSerializer): class Meta: model = KioskShelfMapping fields = ['id', 'mapped_shelf_basket_name_reference', 'mapped_shelf_name', 'mapped_kiosk_name', 'shelf_position'] depth = 2 and this is my views.py file: class ShelfBasketViewSet(APIView): def get(self, request): shelfBasketMappingData = ShelfBasketMapping.objects.all().select_related("mapped_basket_name_reference") print(shelfBasketMappingData) serializer = ShelfBasketMappingSerializer(shelfBasketMappingData, many=True) response = {'status':1, 'message':"Shelf Basket Mapping List", 'data':serializer.data} return JsonResponse(response, safe=False) I am … -
django - [is_superuser, is_staff] Django Admin Category permission options
I have given [is_staff] access to only a few models and cannot access models that have not. But [is_staff] can see the total list of models. I hope [is_staff] cannot see the categories of models that are not accessible. Is there a way? -
Get the type of polymorphic model
I have this model that extends Polymorphic Model models.py class Orders(PolymorphicModel): def get_cat(self): // if self.category == food class Food(Orders) class Item(Orders) I have to identify the type of the polymorphic model. I can't find any way.