Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin page outdated? showing nonexistent model
My django admin page is still showing a model I used to have. I have deleted this model in the code, Then I updated the imports / serializers and registered the new model I made to admin: admin.site.register(watcher_item_tracker_db) and then ran python .\manage.py makemigrations python .\manage.py migrate I have also tried: python manage.py migrate --run-syncdb However, when I go to the admin page for django I can still see the old model I used to have, and I cannot see the new model. Whenever I click on the old model that should not be there, I get this error: OperationalError at /admin/jobs/selenium_watcher_item_db/ no such table: jobs_selenium_watcher_item_db Request Method: GET Request URL: http://10.0.0.233:8000/admin/jobs/selenium_watcher_item_db/ Django Version: 3.1.1 Exception Type: OperationalError Exception Value: no such table: jobs_selenium_watcher_item_db There is no mention of "selenium_watcher_item_db" in my code anywhere after I replaced it with the new item, I tried everything I could think of other than restarting. -
I keep getting this error when i want to query data from a model in mysql database : AttributeError: 'str' object has no attribute 'utcoffset'
This is the code from my Django shell from Inec_results.models import PollingUnit, Lga local = Lga.objects.all() print(local) And I get this error all the time I try to query that model. I'm new to Django please help me out Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\query.py", line 68, in __iter__ for row in compiler.results_iter(results): File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\models\sql\compiler.py", line 1149, in apply_converters value = converter(value, expression, connection) File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\db\backends\mysql\operations.py", line 311, in convert_datetimefield_value value = timezone.make_aware(value, self.connection.timezone) File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\utils\timezone.py", line 262, in make_aware if is_aware(value): File "C:\Users\olaniran\.virtualenvs\BincomDev-TkuS52cz\lib\site-packages\django\utils\timezone.py", line 228, in is_aware return value.utcoffset() is not None AttributeError: 'str' object has no attribute 'utcoffset' -
Django pip freeze > requirements.txt not getting the exact packages installed in the virtual env
Django pip freeze > requirements.txt not getting the exact packages installed in the virtual env rather it's getting all the packages i have ever installed and it's kinda not what i exactly wants, let me show some image of whats happening there are still more packages below, please what can i do -
Can't refresh image on pythonanywhere website
Good evening! I have created a webapp using Django framework. I have replaced a file in the /static/ folder locally (and put the same name for the new file). Then I pushed those changes to my GitHub repo and pulled them using bash console for my pythinanywюhere web app. Then I tried to reload the page, but I got the following message on pythonanywhere: "Your webapp took a long time to reload. It probably reloaded, but we were unable to check it". The file was not replaced and the webpage shows and old version of image. What should I do with this situation? I can't even suggest what the problem is. -
Adding Field Manually in DJango Form
I am making a login system in django, I want the Data of My Forms to Save in The in-built "User" table and my custom made "coders" together. My Form Has 6-7 fields which i want to insert in custom table. but I can only insert "username" and "password" in "User" table. I cant figure out how i can separate "username" and "password" from "FORM" . Here is My Code def f1(request): form = codersform() form2 = User() if request.method == 'POST': form = codersform(request.POST) if form.is_valid: form.save() form2 = coders.objects.filter('name', 'pasw') form2.save() user = form.cleaned_data.get('name') messages.success( request, "Account Created Successfully For " + user) return redirect('login') else: messages.error(request, "Please Fill Out All Fields Correctly") return render(request, 'signup.html', {'form': form}) Thanks :) -
Package libffi was not found in the pkg-config search path Docker
I would like to install some Django packages including django-rest-auth and django-allauth. These packages are able to be installed in my local venv but when building and running Docker containers they give exit code 1 with the errors: Package libffi was not found in the pkg-config search path. -
Simplify writing if/else collection of Django queries
I have code in a Django views.py that looks like: if query_type == 'list': if column == 'person': person_qs = Person.objects.filter(Person__in = query_items_set) elif column == 'grandparent': person_qs = Person.objects.filter(grandparent__name__in = query_items_set) elif column == 'child': person_qs = Person.objects.filter(child__name__in = query_items_set) elif query_type == 'regex': if column == 'person': person_qs = Person.objects.filter(Person__regex = regex_query) elif column == 'grandparent': person_qs = Person.objects.filter(grandparent__name__regex = regex_query) elif column == 'child': person_qs = Person.objects.filter(child__name__regex = regex_query) When it comes to writing views, is there a more accepted/concise way of avoiding repitition, while still maintaining readability and extensibility? -
ModelMultipleChoiceField is not working with UUID as primary key
I have a scenario where I have a field that is hidden....and when this field is a normal PK as generated by Postgresql all is well. When I change said PK to a UUID instead...not so much. When the field is defined as a normal PK the form submits fine. When it's a UUID...I get SELECT A VALID CHOICE....... class AuthorForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(AuthorForm, self).__init__(*args, **kwargs) self.fields['book'] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=Author.objects.filter(author=user).exclude(Q(is_active="False")),required=False) The above works fine if Author PK is a normal PK. When it's a UUID...that's when it won't submit. I've read about this and it would appear that you have to override the selections somehow as a possible answer..so I tried... class AuthorForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(AuthorForm, self).__init__(*args, **kwargs) self.initial['book'] = [c.pk for c in Author.object.filter(author=user)] But it still gives me that same error...SELECT A VALID CHOICE..... Anyone else run into this? -
Django-filter does not filter
I have a project model that is connected to manytomany with a user. Initially, I create a queryset that includes all the projects of the logged in user. The queryset contains two projects, one of them author = False. After I filter it as /project/list/?Shared=True but this does not work. After filtering, there should have been only one project left, but still two are returned, I cannot understand what this is connected with model class Project(models.Model): name = models.CharField(max_length=255, blank=True, null=True) members = models.ManyToManyField(User, through="UserProject", related_name="project") class UserProject(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) author = models.BooleanField(default=False) api class ListProjectApi(ListApi): serializer_class = ProjectSerializer lookup_field = "id" queryset = Project.objects.all() filter_backends = (DjangoFilterBackend,) filterset_class = ProjectFilter def get_queryset(self): user = self.request.user projects = user.project.all() return projects filter class ProjectFilter(rest_framework.FilterSet): author = rest_framework.BooleanFilter(field_name="author", method="filter_author") shared = rest_framework.BooleanFilter(field_name="shared", method="filter_shared") class Meta: model = Project filter_fields = ["author", "shared"] def filter_author(self, queryset, name, value): if name == "author" and value is True: logger.info(queryset) projects = queryset.filter(userproject__author=True) logger.info(projects) return projects logs 2021-12-24 17:54:59,927 ruchnoi INFO <QuerySet [<Project: test>, <Project: author>]> None 2021-12-24 17:54:59,932 ruchnoi INFO <QuerySet [<Project: test>, <Project: author>]> None -
uploading file is not working in django update forms but working in create
i'm using a forms to create and update a form. template and form is the same but view is different. the problem is uploading image is working in create but not in update. no file will not be applied and in post method i receive i get this: /media/<filename> it seems that upload_to path is not applied and no file is uploaded. here is the model: image = models.ImageField(upload_to='%Y/%m/%d', null=True, blank=True) and here is the form: image = forms.ImageField(label='Image', required=False, allow_empty_file=True) and here is the template: <form enctype="multipart/form-data" action="{% if edit == True %}{% url 'update' device_type serial_number %}{% else %}{% url 'addItem' %}{% endif %}" method="POST"> {% csrf_token %} <div style="padding-right: 20px; padding-left: 20px"> {{ form.image.label }}: {{ form.image }} </div> <button type="submit" class="btn">submit</button> </form> above codes are simplified btw. anyone knows why this happening. -
How can I upload to different buckets in Django and Google Storage?
I'm able to upload a file in Google Storage but the problem is that it goes to the default bucket where my static files are: GS_BUCKET_NAME='static-files' I'd like to continue uploading the static files to the 'static-files' bucket, but I would like to also upload the user files to a different bucket: 'user-upload-files' How can I do this in Django 3.2.7, Python 3.9.7 For reference, right now I'm doing: from django.core.files.storage import default_storage file = default_storage.open(filename, 'w') file.write('testing'') file.close() -
How can I control the column order using 'annotate', 'values' and 'union' in Django?
I have 2 models: class Hero(models.Model): name = models.CharField(max_length=50) age = models.PositiveSmallIntegerField() identity = models.TextField(max_length=50) class Villain(models.Model): villain_name = models.CharField(max_length=50) age = models.PositiveSmallIntegerField() identity = models.TextField(max_length=50) and I create some test instances: Hero(name="Superman", age=30, identity="Clark Kent").save() Hero(name="Iron Man", age=35, identity="Tony Stark").save() Hero(name="Spider-Man", age=18, identity="Peter Parker").save() Villain(villain_name="Green Goblin", age=45, identity="Norman Osborn").save() Villain(villain_name="Red Skull", age=38, identity="Johann Schmidt").save() Villain(villain_name="Vulture", age=47, identity="Adrian Toomes").save() Since the Villain model doesn't have a name field, we use annotation before doing a union. Then, using them in a union produces results where the columns aren't all where they should be: >>> from django.db.models import F >>> characters = Hero.objects.all().values('name', 'age', 'identity').union(Villain.objects.all().annotate(name=F("villain_name")).values('name', 'age', 'identity')) >>> for character in characters: ... print(character) {'name': 38, 'age': 'Johann Schmidt', 'identity': 'Red Skull'} {'name': 45, 'age': 'Norman Osborn', 'identity': 'Green Goblin'} {'name': 47, 'age': 'Adrian Toomes', 'identity': 'Vulture'} {'name': 'Iron Man', 'age': 35, 'identity': 'Tony Stark'} {'name': 'Spider-Man', 'age': 18, 'identity': 'Peter Parker'} {'name': 'Superman', 'age': 30, 'identity': 'Clark Kent'} Looking at the raw sql queries, we see this: >>> str(Hero.objects.all().values('name', 'age', 'identity').query) 'SELECT "myapp_hero"."name", "myapp_hero"."age", "myapp_hero"."identity" FROM "myapp_hero"' >>> str(Villain.objects.all().annotate(name=F("villain_name")).values('name', 'age', 'identity').query) 'SELECT "myapp_villain"."age", "myapp_villain"."identity", "myapp_villain"."villain_name" AS "name" FROM "myapp_villain"' The auto-generated sql contains columns that aren't in the same order for … -
celery flower connection issue with --persistent True
I was running celery flower 1.0.0 as a systemd service with --persistent=True. And every time on restarting the service, it didn't use to restart successfully, instead, it used to throw error SSLV3_ALERT_HANDSHAKE_FAILURE. Upon removing --persisten=True it used to work perfectly on every restart, but then I couldn't get my celery flower database be intact after each restart. Here is what worked for me. -
Is there any way to keep tasks running on server side in django?
Basically i have a bot in my django webapp when given your social media credentials it manages your one of social media accounts i was able to succesfully run it while the client is still on website and as you would expect it stopped when the client closed the website. Is there any way to store the credentials and then keep the bot running even after user leaves website and so that bot still manages the account? The bot is mostly making few requests and API calls. Thank You -
Is it better to make custom registration with editing Django UserCreationForm class or make it on a new table and class?
I wanted to make a Django authentication but I was confused about wichone is better? is it is better to edit the venv/Lib/site-packages/django/contrib/auth/forms.py file and make my custom form and edit DB on venv/Lib/site-packages/django/contrib/auth/models.py or it's better to make my authentication system with model and views and forms on my application? -
django.core.exceptions.FieldError: Cannot resolve keyword 'duration' into field when trying to select a property field
there are alot of questions on this particular error but none caused by trying to select a property field from the serializer, below are my code # seriliazer.py class ProjectActivitySerializer(serializers.ModelSerializer): is_running = serializers.ReadOnlyField() duration = serializers.ReadOnlyField() # i am trying to select this particular field to perform some calculation class Meta: model = ProjectActivity fields = '__all__' class GetTotalProjectActivityTime(ListAPIView): """ """ serializer_class = ProjectActivitySerializer permission_classes = (IsAuthenticated, IsOwner|IsAdminUser) # protect the endpoint def get_queryset(self): return ProjectActivity.objects.filter(user=self.kwargs['user'], project__id=self.kwargs['project']).values('duration') Just a background to my problem here: i have the below response [ { "id": 1, "is_running": true, "duration": "2 days, 5:43:26", "description": "worked on developing dashboard endpoint", "start_time": "2021-12-22T11:40:49.452935Z", "end_time": null, "project": 1, "user": 1 } ] I want to run a calculation on the duration but the duration field isn't part of my model field but a just property. now i am finding it difficult to run the caculation -
I am stuck with this problem when I trying to do
when I am going to try this error arises def showsaleF(request): sobj=Sale.objects.all() ob=Sale.objects.values_list('Customer_id') customername=Customer2.objects.raw('SELECT Customer_Name FROM customer_table WHER id=%s',[ob]) productobj=Product.objects.all() mylist = zip(sobj,customername,productobj) return render(request, 'showsale.html',{'sobj':mylist}) ProgrammingError at /showsale (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'id='<QuerySet [(1,), (1,), (1,), (2,)]>'' at line 1") -
can I use like django signals functions in node.js
when the user registers, a new object is added to the user model, at which time a new object must be added to the profile model, the user and profile models are linked. With Django’s signal pack, this thing was pretty easy but I can’t do it on node.js -
How can I Style the forms in Django?
Hello fellow developers, I am struggling to style forms in Django. I have tried it once somewhat 3 to 4 months that time it worked but this time it's not working I am not sure that I doing it the correct way. I want to style the above form to look like the below form. new_sales.html(Working one) {% load static %} {% load crispy_forms_tags %} {% load widget_tweaks %} <!DOCTYPE html> <html> <head> <title>Sales | New</title> <link rel="stylesheet" href="{% static 'resoures/css/style.css' %}"> <link rel="stylesheet" href="{% static 'vendors/css/1.3 grid.css.css' %}"> <link rel="stylesheet" href="{% static 'vendors/css/ionicons.min.css' %}"> <link rel="stylesheet" href="{% static 'vendors/css/hint.css' %}"> <link rel="stylesheet" href="{% static 'vendors/css/normalize.css' %}"> <link href="https://unpkg.com/ionicons@4.5.10-0/dist/css/ionicons.min.css" rel="stylesheet"> </head> <body> <nav> <div class="nav_box--img-box"> <img src="{% static 'resoures/img/Me.jpg' %}" alt="Owner Image"> </div> <div class="nav_box--heading-box"> <h1>Harishree Chemist</h1> <h3>Medical Retailer</h3> </div> <div class="nav_box--menu-box"> <a href="#"><span class="ion-ios-search"></span> Search</a> <a href="{% url 'purchase' %}"><span class="ion-ios-log-in"></span> Purchase</a> <a href="{% url 'Sales' %}" style="border-left: 5px solid var(--light-blue); background-color: hsl(194, 100%, 95%);"><span class="ion-ios-log-out"></span> Sales > <span class="ion-md-add-circle-outline"></span> Add New Bill</a> <a href="{% url 'Stocks' %}"><span class="ion-ios-cube"></span> In Stock</a> <a href="#"><span class="ion-ios-analytics"></span> Analytics</a> </div> <div class="nav_box--user-box"> <a href="#">Log out</a> </div> </nav> <main> <div class="first-box"> <div class="row"> <div class="col span-3-of-9"> </div> <div class="col span-3-of-9"> <h1 class="heading" style="text-align:center">Add New … -
Heroku release fails, error related to django.utils
So I updated my python code to Django 4.0 and with that, had to remove and update some deprecated code as "ungettext_lazy" and similar. Locally, the code is compiling well but when I push it to heroku, I get this error: from django.utils.translation import ungettext_lazy ImportError: cannot import name 'ungettext_lazy' from 'django.utils.translation' (/app/.heroku/python/lib/python3.9/site-packages/django/utils/translation/__init__.py) I've tried a few things but haven't been able to update this on heroku. -
Django rest framework ListApiView slow query
I have a displays table with 147 rows. I am not doing any heavy computation on this data set I just need to get it fast from the database. For now, the load time is 3-4 seconds. Other data comes really fast, why? Does the ListApiView work slow? @permission_classes([AllowAny]) class DisplaysList(generics.ListAPIView): queryset = Displays.objects.all() serializer_class = serializers.DisplaySerializer -
How to resolve an error after deploy on heroku?
After deploy I have an error whenever I try to push a button. What to do? Text of error: ProgrammingError at /notion/ relation "base_notion" does not exist LINE 1: ... "base_notion"."title", "base_notion"."body" FROM "base_noti... -
How to connect redis heroku for websocket?
I'm making chat. I need to deploy my django app to heroku. I did it via the docker. I use free heroku redis and django-channels. Redis cancels my connection and I'm getting ConnectionResetError: [Errno 104] Connection reset by peer In settings i have CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get("REDIS_URI")], }, }, } And my REDIS_URI I got from heroku-resources-heroku_redis-settings consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print('==================================') print('==================================') print(self.room_name) print(self.room_group_name) print('==================================') print('==================================') await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() .................... And the traceback 2021-12-24T15:59:15.190002+00:00 heroku[router]: at=info method=GET path="/ws/chat/FIRST/?access=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjQwMzY1MDY5LCJpYXQiOjE2NDAzNTQyNjksImp0aSI6ImZiNTg2N2MzNzg4NzRiN2M4NmJjNzM1YTJmNmQ1MTFmIiwidXNlcl9pZCI6MX0.JPPRPZAWE0iJ9BqBXYNZLc27u_CNqX90zX9F6MMJpf4" host=ggaekappdocker.herokuapp.com request_id=47782ca1-01c4-42e5-a589-5502869d2393 fwd="178.121.19.23" dyno=web.1 connect=0ms service=569ms status=500 bytes=38 protocol=https 2021-12-24T15:59:14.973191+00:00 app[web.1]: 2021-12-24 15:59:14,972 INFO ================================== 2021-12-24T15:59:14.973292+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO ================================== 2021-12-24T15:59:14.973402+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO FIRST 2021-12-24T15:59:14.973507+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO chat_FIRST 2021-12-24T15:59:14.973604+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO ================================== 2021-12-24T15:59:14.973719+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO ================================== 2021-12-24T15:59:14.974246+00:00 app[web.1]: 2021-12-24 15:59:14,974 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-24T15:59:14.975178+00:00 app[web.1]: 2021-12-24 15:59:14,975 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-24T15:59:14.979031+00:00 app[web.1]: 2021-12-24 15:59:14,978 DEBUG Cancelling waiter (<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f3c21189c40>()]>, [None, None]) 2021-12-24T15:59:14.979466+00:00 app[web.1]: 2021-12-24 15:59:14,979 DEBUG Closed 0 connection(s) 2021-12-24T15:59:14.979729+00:00 app[web.1]: 2021-12-24 15:59:14,979 DEBUG Cancelling waiter (<Future cancelled>, [None, … -
cannot upload HTML image to a website, however local file URL works fine
before you say that it's a duplicate, please read the entire thing. I have the following piece of code: <title>the-doge.net</title> <!-- add the image--> <img src="doge-poster1.png" height="500" width="800" style="display: block; margin-left: auto; margin-right: auto;"/> <body style="background-color:black;"> <!--add the login and register buttons--> <input type="image" src="register.png" style="display:inline; position:absolute; top:50px; right: 7%;"/> <input type="image" src="login.png" style="display:inline; position:absolute; top:50px; left: 12%;"/> </body> however, it says Not Found: /login.png Not Found: /doge-poster1.png Not Found: /register.png I have looked at various answers on Stack Overflow, including this, and also a few websites like here and provided full directory, and a image on img.bb, but it all did not work. Here is my file structure: ... landing(folder) --migrations (folder) --templates (folder) ----landing (folder) ------base.html ------doge-poster1.png ------index.html ------login.png ------navbar.html ------register.png note: In PyCharm there is a way to open a local file URL and it works fine, but python manage.py runserver doesn't seem to display any of the images. -
How to hash strings in python(django) and compare the hashed value with a given string
I'm working on a web app that allows users to sign up then login, I used the following functions to hash the password from passlib.hash import pbkdf2_sha256 import math def encrypt_password(pswd): encrypt_pswd = pbkdf2_sha256.encrypt(pswd, rounds=(int(math.pow(len(pswd),3))), salt_size=(len(pswd)*2)) return encrypt_pswd def verify_password(pswd, e_pswd): en_pswd = encrypt_password(pswd) if en_pswd == e_pswd: return True else: return False my problem is that the string I hashed doesn't produce the same result when I hash it for a second time. How can I resolve this issue or what methods can I use hash the password, store in the database and compare that value with the one from the login form