Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mysql 5.7 breaking tests ( mysql connection gone )
I am facing a test failures while updating a code from mysql5.6 to 5.7. Only one test which is using multiprocessing.Process is failing. MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') The above exception was the direct cause of the following exception Is there any change in related with threading in mysql5.7 or i am missing some thing ? -
How to add tasks to a different tiles with ONE tile - Many Tasks relation?
I am trying to relate a tile for several tasks to django, but simply the relationship continues to give error when I try to add a second task to the same tile. I leave the code of the different models below and the respective error: class Tile(models.Model): STATUS = Choices('Live', 'Pending', 'Archived') launch_date = models.DateTimeField(editable=False, auto_now_add=True) status = models.CharField(choices=STATUS, default=STATUS.Live, max_length=25) def __str__(self): return "Tile date -> " + str(self.launch_date) + " with status -> " + self.status class Task(models.Model): TYPES = Choices('Survey', 'Discussion', 'Diary') tile = models.ForeignKey(Tile, on_delete=models.CASCADE) title = models.CharField(max_length=100) order = models.IntegerField() description = models.CharField(max_length=500) task_type = models.CharField(choices=TYPES, default=TYPES.Survey, max_length=25) def __str__(self): return str(self.tile) + " " + self.title I try to add a second task to the same tile and: In the end you are supposed to be able to add several different tasks to the same tile in the following way: Please, what is the problem right here? -
Database for django deployed application
I have a Django website where you can fill a form and after that you can upload/download files. I'm using PostgreSQL database and everything works well locally. If I deploy the site on the server (using cloud foundry) and I want to upload a file, I receive this error: relation "Upload_Page_form_data" does not exist I understand that the db it's not created on the server but my question is how this process it's working? After creating the model in Django, my db is automatically generated. But when i want to deploy the application, I have to manually create the tables, rows and colls for being available on the server? If yes, how? -
Django {% extend static "template.html" %} throwing TemplateSyntaxError
I have a template.html file full of some boiler plate html text. Then in index.html I have: {% load static %} {% extends static 'template.html' %} In settings.py I have (relevent things): INSTALLED_APPS = [ 'notes.apps.NotesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' However, when I try to render index.html I get a TemplateSyntaxError at 'extends' takes one argument. When template.html was placed in the same directory as index.html and I used {% extends 'template.html' %} everything worked fine. -
Dot notation request handling in Django Rest Framework
I have a serializer class (Not ModelSerializer) that needs to take a list of dot notation configuration from the request: class ConfigurationSerializer(serializers.Serializer): a_value= serializers.CharField( required=False, source='a.value', ) I thought by specifying the source attribute, the serializer will know a.value in the request.data will represent a_value in the ConfigurationSerializer. But when I run the serializer.is_value(), I don't see any data inside serializer.data: def post(self, request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): print(serializer.data) #-----> this is empty Is it the correct way to do it? How can I translate the dot notation from the request object to serializer? -
Page not found: No CustomUser matches the given query
Summary of project: (Sorry if this post is too long). You post a funny comment and people can read your post and then click a button to like you. If you liked their post and they liked yours then you can both chat. Summary of problem: Any time I click the "like" button on a post I get the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/vote/ Raised by: users.views.ProfileDetailView - No CustomUser matches the given query. So basically I cannot get the "like" button to save the current user + the post author to the "liked" table. I've spent like two weeks reading the Django docs and trying different things in the view but now I'm just lost... I think it's my URL... Setting.py AUTH_USER_MODEL = 'users.CustomUser' Users/models.py class CustomUser(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField( get_user_model(), on_delete=models.CASCADE, primary_key=True, ) first_name = models.CharField(max_length=100, blank=True) def __str__(self): return f'{self.user.username}' Userpost/models.py class Posts(models.Model): date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) caption = models.CharField(max_length=160, blank=True) def __str__(self): return self.caption Voting/Models.py class Like(models.Model): liker = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='liker', ) likee = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='likee', ) date_created = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): super(Like, self).save(*args, **kwargs) … -
Dango & Vue.Js project
I've been building a lot of test websites in Django, and took an online course in Django + Vue.JS, but I'm not 100% comfortable yet (with Vue.js and bigger projects). So I have a question. First a small description about my idea; I want a basic home page, just some information about my service, with some additional pagel about, learn, products, etc. You get it. Then there has to be a user register/login section. I've created one before with an email verification, but I also want to add a monthly payment (any tips/tutorials are welcome). After you've registered and logged in, you have to be redirected to the Web-App I want to build. In the web-app I want to build a few different apps, let's say; I want to build a stock analyse app. Where every analysing tool has other calculations, etc. The question I have; How does the architecture of the app should look like? Should I have a home-app, user-app, stock-app? Where only the stock-app has to be combined with Vue.js, how to make this happen? And how to make sure only logged in users can access the web-app? Or is this possible with @login_required? Hope someone can … -
Admin folder inside template folder
So I have created a template folder inside my project (project/template). Inside the template folder I've created a subfolder called admin (project/template/admin). Now the issue is that whenever I try to access the Django admin page, it redirect me to the page inside the subfolder(project/template/admin/index.html) Is there a way around this? -
AttributeError: 'NoneType' object has no attribute 'startswith' while launching the Django App
while running the command >python manage.py runserver to launch the app getting the below error, is there any package needs to be updated?? File "D:\venv\lib\site-packages\django\db\backends\mysql\base.py", line 201, in get_connection_params if settings_dict['HOST'].startswith('/'): AttributeError: 'NoneType' object has no attribute 'startswith' -
Implementing pdb debugger in django ace editor
How could I implement pdb debugger in django ace editor so that the user can debug the code and see the debug output in browser console. If anyone can suggest or guide something then that will be great help. -
"detail": "Authentication credentials were not provided." in every api call in django
Iam developing authentication using token in django rest. I successfully developed the login api view where, the token is generated and returned after user is logged in using the credentials. But now my other simple get apis of blog posts and also sign up api is asking for token, when I call that api. For eg: when i call http://127.0.0.1:8000/api/blog-post , it is giving "Authentication credentials were not provided." I dont want this. I dont need users to log in to simply view the blog posts on my web. How to solve this?? This is my login view class LoginUserView(GenericAPIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) return response.Response({"token": token.key}, status=status.HTTP_200_OK) This is my login user serializers class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(label='Email Address') class Meta: model = User fields = [ 'email', 'password', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): # user = None email = data.get("email", None) password = data.get("password") if not email: raise serializers.ValidationError("Email is required for login") if not password: raise serializers.ValidationError("Password is required for login") user = authenticate(email=email, password=password) if not user: raise serializers.ValidationError("This email is … -
how to get the request values using signals, to be able to instantiate a chat object
I'm finishing a college project and I'm stuck on generating notifications whenever a user sends a message to another, I have a notification model, but I'm not able to send the message to the notification in django admin I can already insert the notification and display the screen, but only manually, when the user sends the message, it is not sent to the notification model :'( from django.db import models from django.db.models.signals import post_save, post_delete class Chat(models.Model): codigoSala = models.CharField(max_length=20, unique=True) locador = models.CharField(max_length=50, blank=False, null=False) locatario = models.CharField(max_length=50, blank=False, null=False) nomeSala = models.CharField(max_length=200, blank=True, null=True) def __str__(self): super().__init__() return self.codigoSala def add_chat(self): sender_message = Chat( self.codigoSala, self.locador, self.locatario, self.nomeSala) sender_message.save() class Mensagem(models.Model): texto = models.CharField(max_length=80) chat = models.ForeignKey(Chat, on_delete=models.CASCADE) def __str__(self): return self.texto def add_message(sender, instance, *args, **kwargs): message = instance here I am not able to get this parameter information, as far as I understand, the signals do not allow the request for an argument (in add_message in my case) these values below are passed in the url, I managed to get the values, but I tried in different ways to solve my real problem that I forgot how I did, now that I found a way to … -
how can i display the result of my sqlite query in a html django page
I have the follwing querry set in my views.py with connection.cursor() as cursor: #cursor.execute("SELECT AgentName FROM 'CSQ Agent Report' ") cursor.execute("SELECT 'AgentName', count (*) FROM 'CSQ Agent Report' WHERE 'AgentName' != 'None' AND 'OriginatorDNHANDELED' = '1' or 'OriginatorDNNOTHANDELED' = '1' Group by 'AgentName'") obj = cursor.fetchall() context = { 'object': obj } return render(request,"CSQ/detail.html", context) and i like to display the result of the querry in my html page which code is : {% extends 'base.html' %} {% block content %} <h1> Stats Call Center Of Feb </h1> <p> Nb of calls received by agent </p> <ul> {% for var in object %} <li> {{var}} </li> {% endfor %} </ul> {% endblock %} I have the same querry created in python and it works as expected : cursor.execute(""" SELECT "AgentName", count (*) FROM "CSQ Agent Report" WHERE "AgentName" != "None" AND "OriginatorDNHANDELED" = '1' or "OriginatorDNNOTHANDELED" = '1' Group by "AgentName" """) liste8= cursor.fetchall() for i in range (len(liste8)): print (liste8[i][0],liste8[i][1]) and the result in python is as follow : Agent1 11 Agent2 41 Agent3 249 Agent4 46 Agent5 2 Agent6 216 Agent7 117 Agent8 242 Agent9 50 I would like to display the same resulat in my Html Django … -
django request.user.is_authenticated returns AnonymousUser after a while
I have a very weird problem with Django authentification/Login. I can log in just fine and I'm able to browse a couple of pages with an authenticated and logged-in user until at some point my request.user.is_authenticated returns False. I then have an AnonymousUser and can't access the user information anymore. This problem is not present on my localhost server and only happens when I try out my production server. I would say this problem occurs every 50% of requests, which means I have one chance out of two that my user keeps its authentication after a redirect. The login() function on my home page works fine everytime I use it so it means the problem arise during the redirect. My setup used to work perfectly until I recently tried to implement a Facebook auth with allauth. I had difficulties to get it running and I suspect this might have caused the present issue. I have since removed every line that was related to the facebook login but I still could not get my production server to run. Here is my settings.py AUTH_USER_MODEL = 'custom_user.CustomUser' INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'custom_user.apps.CustomUserConfig', 'user_profile', 'rest_framework', 'django_email_verification', ] … -
How to use model attribute in both POST and GET in Django
I am getting an attribute called Number using POST method. Also I have a form in my template with GET method.For that form,I need to use the Number but it returns None. views.py def recognition(request): tableFilter = '' if request.method == "POST": Number = request.POST.get('Number', None) meter = Meter.objects.get( Number= Number) if request.method == "GET": ************Here I need to use meter existing in POST part(first if)********* object_list = Report.objects.filter(meter=meter) tableFilter = RecordFilter(request.GET, queryset=object_list) context = { 'meter':meter, 'table_filter':tableFilter, } return render(request, 'services/specificMeterDelete.html',context) How can I access Number in GET part? Thanks. -
Django if now = post date in template
I'm a bit lost, In my MySQL DB DateField is saved like that 2020-10-29 In my template I try to see if DateField == Now. In my models it's DateField not a DateTimeField So I've try to do this: {% now "Y-F-j" as current_date %} {% if post.start_date == current_date %} Today{% else %} Ended{% endif %} But even if it should match I got ended everywhere... Do you have any idea? -
Django-admin is not doing anything?
I am trying to create a web app and have installed Django. I have the latest version of it and pip. When I run django-admin startproject mysite, nothing happens. I have installed the path to the bin folder for django on my environment variables and still the commands are being ignored. I can create a virtual environment and still django-admin is being ignored. Is the folder being created in a different file location? Please help I am so lost right now. -
Django template not detecting certain keys while iterating over a dict
I am facing this weird issue: These are three rows of a 'table' passed by view.py as printed out in Django template: {'c2': {'tag_id': 'c2', 'display_id': 'C0002', 'name': 'Financial Statements', 'class': 'child-of-None', 'type': 'category', 'statement': 'N/A', 'jun_20': 0, 'jul_20': 0, 'aug_20': 0}, 'c1': {'tag_id': 'c1', 'display_id': 'C0001', 'name': 'Balance Sheet', 'class': 'child-of-2', 'type': 'category', 'statement': 'N/A', 'jun_20': 0.0, 'jul_20': 0.0, 'aug_20': 0.0}, 'c6': {'tag_id': 'c6', 'display_id': 'C0006', 'name': 'Non-Current Assets', 'class': 'child-of-1', 'type': 'category', 'statement': 'N/A', 'jun_20': 0.0, 'jul_20': 36750000000.0, 'aug_20': 0.0}} This is a list of 'months' passed by views.py as printed out in Django template: ['jun_20', 'jul_20', 'aug_20'] And this is the code I am using to generate a table row: {% for content in table.values %} <tr> <td>{{ content.display_id }}</td> <td>{{ content.name }}</td> {% for month in months %} <td>{{ content.month }}</td> {% endfor %} </tr> {% endfor %} And this is the output: <tr> <td>C0002</td> <td>Financial Statements</td> <td></td> <td></td> <td></td> </tr> <tr> <td>C0001</td> <td>Balance Sheet</td> <td></td> <td></td> <td></td> </tr> <tr> <td>C0006</td> <td>Non-Current Assets</td> <td></td> <td></td> <td></td> </tr> Why are the month td tags blank? If I change 'content.month' to 'content.jul_20, the tags do get the dictionary values for jul_20. I also tried converting the numbers stored … -
I used str() on string with byte literal, how do I reverse the operation?
So I had binary like the following b"My name is ...\n blah blah" then I used I used str() on it which resulted in "b'My name is ...\\n blah blah'" how can I undo this and get a variable with byte literal again? -
Vue.js instant search from API REST Framework using axios
I have a problem. I want to create instant search, without any search button, that when i'm typing e.g. more than 3 letters, my results will be instant show below. My code: <template> <div class="nav-scroller py-1 mb-2"> <div class="nav d-flex justify-content-between"> <input v-model="keyword" class="form-control" type="text" placeholder="Search" aria-label="Search"> <div v-bind:key="result.id" v-for="result in results"> <p>Results are: {{ result.title }}</p> </div> </div> </div> </template> <script> import axios from 'axios'; export default { name: 'Home', components: { }, data() { return { keyword: '', results: [], } }, methods: { getResults() { axios.get("http://127.0.0.1:8000/api/v1/books/?search="+this.keyword) .then(res => (this.results = res.data)) .catch(err => console.log(err)); } }, created() { this.getResults() } } </script> Could you help me? -
Access private data .env file in gitlab CI django
I am stuck in a issue I dont want to commit my .env file on gitlab, but during CI I need that values for database configuration like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'postgres', 'PORT': '5432' } } while my file in actual DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT", cast=int), } } so what is possible way to assign these values to run tests.py in CI gitlab -
I need to get a blank json field on my Django and collect it as error
So far this is my code. def post(self, request): if serializer.is_valid(): if not request.data['valor_sensor']: request.data['valor_sensor'] = "ERRO" serializer = serializers.EventosSerializer(data=request.data) serializer.save() return Response(serializer.data, status.HTTP_201_CREATE I need to take the field valor_sensor, from this json, and when I collect it, IF IT IS BLANK, I need to transform it into the string "ERROR". Anyone knows how to do it? -
Conda command not found on deploying a django project to heroku
I have a django project which uses rdkit library, which is depended on conda environment. But I cannot deploy the project to heroku. When I try git push heroku master it is showing the following errors: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python/Conda app detected remote: -----> Preparing Python/Miniconda Environment (3.8.3) remote: /tmp/codon/tmp/buildpacks/298b2b29cc393b8d85322805d763db20318c981c/bin/steps/conda_compile: line 9: conda: command not found remote: ! Push rejected, failed to compile Python/Conda app. remote: remote: ! Push failed remote: Verifying deploy... I have not created any requirements.txt file because to use rdkit I have to use rdkit channel, and I cannot find a way to specify that in requirements.txt. Instead I have used environment.yml. The environment.yml contains: name: Phytochem channels: - rdkit - defaults - conda-forge dependencies: - _libgcc_mutex=0.1 - blas=1.0 - bzip2=1.0.8 - ca-certificates=2020.6.20 - cairo=1.14.12 - certifi=2020.6.20 - dj-database-url=0.5.0 - django=3.1.2 - django-heroku=0.3.1 - fontconfig=2.13.0 - freetype=2.10.4 - glib=2.63.1 - icu=58.2 - intel-openmp=2020.2 - jpeg=9b - krb5=1.16.4 - lcms2=2.11 - ld_impl_linux-64=2.33.1 - libboost=1.73.0 - libedit=3.1.20191231 - libffi=3.2.1 - libgcc-ng=9.1.0 - libpng=1.6.37 - libpq=11.2 - libstdcxx-ng=9.1.0 - libtiff=4.1.0 - libuuid=1.0.3 - libxcb=1.14 - libxml2=2.9.10 - lz4-c=1.9.2 - mkl=2020.2 - mkl-service=2.3.0 - mkl_fft=1.2.0 - mkl_random=1.1.1 - ncurses=6.2 - numpy=1.19.2 - … -
ValueError at /cart/remove/ could not convert string to float:
This code is showing me an error. def removeFromCart(request): request.session.set_expiry(0) obj_to_remove = int(float(request.POST['obj_id'])) obj_index = request.session['cart'].index(obj_to_remove) request.seession['cart'].pop(obj_index) return redirect('cart') -
how to pass multiple admin class with iterable in django admin
from django.contrib import admin from .models import Post, Comment, DataTracking myModels = [Comment, DataTracking] @admin.register(myModels, safe=True) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'created_on', 'active') list_filter = ('active', 'created_on') search_fields = ('name', 'email', 'body') actions = ['approve_comments'] def approve_comments(self, request, queryset): queryset.update(active=True) class DataTrackingAdmin(admin.ModelAdmin): list_display = ('blogtitle','country','viewcount') list_filter = ('blogtitle','country') search_fields = ('blogtitle','country','viewcount') class PostAdmin(admin.ModelAdmin): class Media: js=("injectjs.js",) list_display = ('title', 'slug', 'status','created_on') list_filter = ("status",) search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} admin.site.register(Post, PostAdmin) i am trying to this i want to register newly added DataTracking model with admin i tried passing both as seprate list admin class and itrables to admin register it gives me error