Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django "static" tag doesn't work with svg
I am using an SVG with a href of /static/portfolios/trillio/img/sprite.svg#icon-chat that works just fine but when I use: {% static 'portfolios/trillio/img/sprite.svg#icon-chat' %} the SVG doesnt' show, but the browser console doesn't show any error, the output for the static is this: /static/portfolios/trillio/img/sprite.svg%23icon-chat is it the %23 that's making a difference and if so how do I fix that? -
column clients_client.position does not exist... then - no migrations to apply
I've added a field in my clients model. Here's the model: class Client(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) email = models.EmailField(null=True, blank=True) position = models.CharField(max_length=30) organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=6, on_delete=models.SET_NULL) company_name = models.CharField(max_length=50 , default=None) street_address = models.CharField(max_length=50 , default=None) baranggay = models.CharField(max_length=50 , default=None) city = models.CharField(max_length=50 , default=None) region = models.CharField(max_length=50 , default=None) date_added = models.DateTimeField(auto_now_add=True) phoned = models.BooleanField(default=False) special_files = models.FileField(blank=True , null=True) def __str__(self): return self.company_name Before I've added the position field the program runs smoothly. Now I've got "ProgrammingError: column clients_client.position does not exist" At Heroku Bash, when I run python manage.py makemigrations, it detects the changes, but when I migrate it says, no migrations to apply. Please help. -
Why User model has type string?
I have a view that returns data corresponded to the user, but when I try to find the User I get this error: Type str has no object method File views.py from .models import Question, User @api_view(['POST']) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def answers_view(request, *args, **kwargs): userstring = request.data["name"] try: user0 = User.objects.get(username=userstring) except ObjectDoesNotExist: user0 = "NotFound" print("USER: ", user0, flush = True) File models.py from django.db import models # Create your models here. import random from django.conf import settings from django.db import models from django.db.models import Q User = settings.AUTH_USER_MODEL -
Django - Images aren't created under media folder once form with a ImageField has been submitted
Does anyone may know what am I doing wrong? Is there any additional config which am I missing? I have also created a media folder under the project root directory. urls.py urlpatterns = [ path('', views.HomeView().get, name='home'), path('admin/', admin.site.urls), path('add_your_bet/', views.AddBetsView.as_view(), name='add_your_bet'), path('add_your_bet/edit/<int:pk>', views.UpdateBetView.as_view(), name='update_your_bet'), path('create_league/', views.CreateLeagueView.as_view(), name='create_league'), path('create_user/', views.CreateUserView.as_view(), name='create_user'), path('members/', include('django.contrib.auth.urls'), name='register'), path('members/', include('members.urls'), name='login'), path('score_predictions/<int:pk>', views.predictions, name='predictions'), path('stats/', views.index, name='stats'), path('terms/', views.TermsView.as_view(), name='terms') ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)``` models.py class LeagueUser(models.Model): user_name = models.ForeignKey(User, on_delete=models.CASCADE) league_name = models.ForeignKey(League, to_field='league_name', on_delete=models.CASCADE) first_name = models.CharField('First Name', max_length=20) last_name = models.CharField('Last Name', max_length=20) nick_name = models.CharField('Nick Name', max_length=20) email = models.EmailField('Email') image = models.ImageField(null=True, blank=True, upload_to='media') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) -
Multiple user models in Django inherited from AbstractBaseUser
I have a "legacy" database with different tables for different user types (admins and customers). They have nothing in common. I need to implement both models in the Django project, users need to log in to the client pages, admins to the admin pages (not django admin). How to solve this deal? Basically, I have an idea to run two application instances with different config values AUTH_USER_MODEL but it looks not the best idea. Thanks in advance. -
How do I show navbar items based on a model field in Django?
I have a Blog model that looks like this: class Blog(models.Model): title = models.CharField(max_length=200) content = models.TextField() slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blogs') parent = models.CharField(max_length=50, choices=PARENT_TUTORIALS) def get_absolute_url(self): return reverse("blog_list", args=[str(self.parent), str(self.slug)]) I can succesfully display all the blogs on a table of contents via my table.html template: {% for blog in blog_list %} <li><a href="{{ blog.get_absolute_url }}">{{blog.title}}</a></li> {% endfor %} However, I want to show only those blogs that have the same Blog.parent value as the current blog page. For example, the page example.com/biology/page1, has biology as a parent. When the user is on that page, the table of contents should show only the pages that have biology as a parent. -
SSL Error accessing azure datastore for Azure Auto ML
I am implementing Azure AutoML dashboard in a docker container. When I access container without Docker it works. But in docker it gives SSL Error. def upload_dataset_to_blob(ws): datastore = ws.get_default_datastore() datastore.upload_files(files=[ '/usr/src/mediafiles/train.csv'], target_path='beeeerrr-dataset/tabular/', overwrite=True, show_progress=True) datastore.upload_files(files=[ '/usr/src/mediafiles/valid.csv'], target_path='beeeerrr-dataset/tabular/', overwrite=True, show_progress=True) datastore.upload_files(files=[ '/usr/src/mediafiles/test.csv'], target_path='beeeerrr-dataset/tabular/', overwrite=True, show_progress=True) train_dataset = Dataset.Tabular.from_delimited_files( validate=False, path=[(datastore, 'beeree-dataset/tabular/train.csv')]) valid_dataset = Dataset.Tabular.from_delimited_files( validate=False, path=[(datastore, 'beeree-dataset/tabular/valid.csv')]) test_dataset = Dataset.Tabular.from_delimited_files( path=[(datastore, 'beeree-dataset/tabular/test.csv')]) return train_dataset, valid_dataset, test_dataset This is the error I am getting Uploading an estimated of 1 files app_1 | Uploading /usr/src/mediafiles/train.csv app_1 | Uploaded /usr/src/mediafiles/train.csv, 1 files out of an estimated total of 1 app_1 | Uploaded 1 files app_1 | Uploading an estimated of 1 files app_1 | Uploading /usr/src/mediafiles/valid.csv app_1 | Uploaded /usr/src/mediafiles/valid.csv, 1 files out of an estimated total of 1 app_1 | Uploaded 1 files app_1 | Uploading an estimated of 1 files app_1 | Uploading /usr/src/mediafiles/test.csv app_1 | Uploaded /usr/src/mediafiles/test.csv, 1 files out of an estimated total of 1 app_1 | Uploaded 1 files app_1 | <bound method DataReference._get_normalized_path of $AZUREML_DATAREFERENCE_blob_test_data> app_1 | Internal Server Error: /azureml/train/ app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python3.8/site-packages/azureml/data/dataset_error_handling.py", line 65, in _validate_has_data app_1 | dataflow.verify_has_data() app_1 | File "/usr/local/lib/python3.8/site-packages/azureml/dataprep/api/_loggerfactory.py", line 206, in wrapper … -
How to upload multiple videos with title to a course in Django
I am working on an e-learning project. It focuses on the relation among Students, Teachers, and Courses. The project allows teachers to create Courses with multiple lessons and students to enrol in these courses. I want to create lessons for each course like this here But I don't know how to do it. Here is my code. models.py class Course(models.Model): instructor = models.ForeignKey(User, on_delete=models.CASCADE, default=None) title = models.CharField(max_length=100, default=None) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, default='') slug = models.SlugField(max_length=200, unique=True, blank=True, primary_key=True, auto_created=False, default='') short_description = models.TextField(blank=False, max_length=60, default='') description = models.TextField(blank=False, default='') language = models.CharField(max_length=200, default='English') thumbnail = models.ImageField(upload_to='thumbnails/', default='') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Course, self).save(*args, **kwargs) def add_user_to_list_of_students(self, user): registration = CourseRegistration.objects.create(user = user, course = self) class Lesson(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='lessons', default='') title = models.CharField(max_length=100, default=None) video = models.FileField(upload_to='courses/') def __str__(self): return self.course.title views.py class CreateCourseView(LoginRequiredMixin, CreateView): template_name = 'courses/upload.html' What should I write in views.py which allow teachers to create courses and multiple lessons in each course? -
Django Unique on ManyToManyField
I'm trying to create a private messaging system between users. I created two models. One is "Message" which contains messages and another one is "Conversation" which contains messages just between two users. I want to head off create duplicate conversations. For example i created a conversation between user1 and user2 and this conversation's ID is "5" then i created another one conversation again between user1 and user2 and it's ID is "6". That's bad for me. There must just one conversation between same users. When i try "unique=True" i'm getting an error as "api.Conversation.participants: (fields.E330) ManyToManyFields cannot be unique." models.py class Conversation(models.Model): participants = models.ManyToManyField(User, unique=True) class Message(models.Model): sender = models.ForeignKey(User, related_name="sender", on_delete=models.CASCADE, related_query_name='s') reciepent = models.ManyToManyField(User) conversation = models.ForeignKey(Conversation, blank=False, null=False, on_delete=models.CASCADE) msg_content = models.TextField(max_length=500, blank=True) sendtime = models.DateTimeField(auto_now_add=True) ordering = ["-sendtime"] -
How to load react's staticfiles from s3 in django - react
So I have a Django - React application. All the static files are served by s3 I ran npm run build and then i coped the build folder into my django project folder. and then i setup the template dirs and staticfiles dirs in my settings.py file. when i try to load the django-admin page. everything works perfectly. the static files are served by aws s3. But when i try to load the react page. it tries to look for static files locally which obviously does not exist. so how do i tell my react app to look for the staticfiles in s3? this is how my index.html looks <!doctype html> <html lang="en"> <head> <meta charset="utf-8"/> <link rel="icon" href="/favicon.ico"/> <meta name="viewport" content="width=device-width,initial-scale=1"/> <meta name="theme-color" content="#000000"/> <meta name="description" content="jgprth."/> <link rel="apple-touch-icon" href="/logo192.png"/> <link rel="manifest" href="/manifest.json"/> <title>test</title></head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script>!function (e) { function t(t) { for (var n, a, l = t[0], f = t[1], i = t[2], p = 0, s = []; p < l.length; p++) a = l[p], Object.prototype.hasOwnProperty.call(o, a) && o[a] && s.push(o[a][0]), o[a] = 0; for (n in f) Object.prototype.hasOwnProperty.call(f, n) && (e[n] = f[n]); for (c … -
Django not setting the same site cookie
I am getting an error in chrome as follows Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being sent in a cross-site request. In Django docs they have given by default it's been set to Lax but then why does the error come I am using Django 3.2.2 -
Grouping the data financial year wise and month wise
I am developing a django restframework API to show data of the salary paid to employees financial Year wise and month wise sum. Something like below: [ "2019-20":{ "Apr":120012, "May":142566, "June":122223 #So on for every month }, "2020-21":{ "Apr":130019, "May":142526, "June":152221 #So on for every month } ] My models are class Months(Model): month_name = models.Charfield(max_length=3) class FinYear(Model): finyear_name = models.Charfield(max_length=7) class Employee(Model): name=models.Carfield(max_length=50) Class Salary(Model): fin_year=models.Foreignkey(FinYear, on_delete=medels.CASCADE) month=models.Foreignkey(Months, on_delete=medels.CASCADE) salary = models.Integerfield(max_length=8) employee_id=models.Foreignkey(Employee, on_delete=models.CASCADE) Any help will be highly appreciated. -
ViewSet and additional retrieve URL
I have a django model that I expose as a ViewSet. Now I want to add an additional URL where a single instance can be retrieved and custom actions can be executed. # models.py class MyModel(models.Model): id = models.AutoField(primary_key=True) third_party_service_id = models.StringField() # views.py class MyModelViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin): def retrieve(self, request, *args, **kwargs): if kwargs['pk'].isdigit(): return super(MyModelViewSet, self).retrieve(request, *args, **kwargs) else: query_third_party_service_id = self.request.query_params.get('third_party_service_id', None) if query_third_party_service_id is not None: try: instance = MyModel.objects.get(third_party_service_id=query_third_party_service_id) catch MyModel.DoesNotExist: raise Http404 return Response(self.get_serializer(instance).data) return Response(status=status.HTTP_404_NOT_FOUND) @action(methods=['post'], detail=True) def custom_action(self, request, *args, **kwargs): pass # urls.py router = routers.DefaultRouter() router.register(r'mymodels', MyModelViewSet) router.register(r'mythirdpartyservices/(?P<third_party_service_id>[0-9]+)', MyModelViewSet) My goal is to have http://localhost:8000/mymodels point at the entire ViewSet. Also I would like to lookup an individual model, by only knowing its third_party_id like follows http://localhost:8000/mythirdpartyservices/1337/ and also executing the custom action like follows http://localhost:8000/mythirdpartyservices/1337/custom_action/. The problem I have is that the second url returns an entire queryset, not just a single instance of the model. -
Get model field values from FK related objects
I've got a structure of FK related objects that looks somewhat like that: class Object3(models.Model): ... requirement = models.ManyToManyField(Requirement, blank=True) class Object2(models.Model): ... parent = models.ForeignKey(Object3, on_delete=models.CASCADE) requirement = models.ManyToManyField(Requirement, blank=True) class Object1(models.Model): ... parent = models.ForeignKey(Object2, on_delete=models.CASCADE) requirement = models.ManyToManyField(Requirement, blank=True) class Requirement(models.Model): ... All of those object have the same non-required field, which is a ManyToManyField, it's basically a requirement that can be set on either level of the structure. What I need to do is when I set the m2m field on the highest level of the structure, Object3, I need related Object2 and Object1 to set the m2m identically, same if I set it on Object2 instance, I need it to be set on the related Object1 instances. What is the most Django-ish way to achieve that? I hope my explanation is clear enough, I'll be more than happy to provide any more information. I've been pulling my hair out with this simple task, but I can't seem to come up with a good solution, hopefully with your help I'll be able to. -
Access django admin page behind Nginx
I am able to access all of my regular endpoints in my Django project, but I'm unable to access the /admin login page. Whenever I try to enter the url/admin I get redirected to my top-url, the same happens in Postman. I have the following Nginx file: location ~ /api { rewrite ^/api(.*)$ $1 break; include uwsgi_params; uwsgi_pass unix:/run/uwsgi/backend.sock; } location /static/ { root /home/m3csadmin/backend; } location / { try_files $uri $uri/ /index.html =404; } What am I missing? -
Django Rest Framework: How to Dynamically return subset of fields
I would like to filter by fields name and get back a subset instead of having back all my fields name. For example here I am filtering by id and name. It should return me only this two dimension in json format. I have found many solution on the site and I have done exactly the same as suggested but I don't have the expected result. Could you please help me ? my view: router = routers.DefaultRouter() urlpatterns = [ path('', include(router.urls)), path('edges/', edge_list), path('edges/<int:pk>/', edge_detail), path('network/<int:pk>/edges/', edges_of_a_network), ] Here a copy past example from https://www.django-rest-framework.org/api-guide/serializers/#example class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) My serializer class which I would like to filter fields. class EdgeSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer): source = serializers.SerializerMethodField(method_name='get_node_source') target = serializers.SerializerMethodField(method_name='get_node_target') road_type = serializers.SerializerMethodField( method_name='get_road_type_id') class Meta: model = Edge fields … -
Unable to make a "Get" call to a django app residing in a docker container from a flask app in another docker container
I am referring to the tutorial, https://www.youtube.com/watch?v=0iB5IPoTDts. At from 1:18:09 in the tutorial, I am supposed to implement this code below [Api call from a flask app in a docker container to a django app residing in another docker container][1] But I keep getting maximum retry error. [Error image][2] It seems like the get request is failing. I referred to the following link How to get the IP address of the docker host from inside a docker container, and tried solutions present in answer 1 and 2, but they give an error 400. I am quite novice in flask and django. Please help. Thanks in advance. [1]: https://i.stack.imgur.com/O0tZf.png [2]: https://i.stack.imgur.com/UozYE.png -
Pass a value to an api and return a specific object
I have created an api where #urls.py router = DefaultRouter() router.register('login', GetUserViewSet, basename='get_user') urlpatterns = [ path('', include(router.urls)), ] #views.py class GetUserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = GetProfileSerializer #serializers.py class GetProfileSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ('password', 'groups', 'user_permissions') The above code returns the list of users when I hit 'http://localhost:8000/api/login/' and the specific user when I hit 'http://localhost:8000/api/login/1/'. Here I want to pass the 'mobile_number' to the api and return the only user with the mobile number. I have achieved it by adding get_queryset() to the views as follows. #views.py class GetUserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = GetProfileSerializer def get_queryset(self): mobile_number = self.request.query_params.get('mobile_number') queryset = User.objects.filter(mobile_number=mobile_number) return queryset But the above code is returning the object in an array. I am following a common response format as given below { "status": true, "message": "Successfully registered your account.", "data": { "id": 1, "first_name": "User", "last_name": "U", "email": "user@gmail.com", "dial_code_id": "91", "mobile_number": "9876543211", } } and I am not able to achieve this with this get_queryset(). Please suggest me the best possible way to achieve this. -
Show a set of car models after the user chooses the car brand in Django forms
I am using Django 3.2 to make an uber clone and that when I want to allow the users to register with their vehicle I first want the user to be able to choose the car brand, and then afterwards choose the car model which is sorted according to the car brand. class Vehicle (models.Model): brand = models.CharField(max_length=60) model = models.CharField(max_length=60) vehicle_colour = models.CharField(choices=COLOURS, max_length=10) vehicle_number = models.CharField(max_length=8) I want to add some choices for the brand and model field, but I feel like I might need some javascript to intervene. Do you know any method that I could use to get this done? Your help is greatly appreciated. Thanks! -
Mpesa object has no attribute 'update'
I would like to update the first item in the database each time a user clicks on a button but I keep getting the error every time, any assistance would be appreciated, below is the snippet. Mpesa.objects.filter(Paid_user=self.request.user, Completed=False).first().update(Completed=True) -
how to create comment tree in django
I need a comment system so can reply a comment to any comment I know how to write models and views and my only problem is showing them in the template For example, maybe a group of comments are like this: comment comment comment comment comment comment comment comment comment comment How can I display this structure in the template? -
ValueError - The view didn't return an HttpResponse object. It returned None instead
My view currently returns an error of The view viajecenter.views.receive_payment didn't return an HttpResponse object. It returned None instead. I tried some of the solutions from other related posts here but of no luck. Here is my function in my views.py file: def receive_payment(request, account_code): template_name = 'receive-payment.html' def get_context_data(self, *args, **kwargs): user = self.request.user context = super(receive_payment, self).get_context_data(*args, **kwargs) account = get_object_or_404(Account, account_code=self.kwargs['account_code']) if user.is_assigned: puv = Puv.objects.get(assignment_id=user.assignment_id) locations = puv.route.locations.all().order_by('distance_from_base') context["account"] = account context["puv"] = puv context["locations"] = locations return render(request, self.template_name, context) else: return user and the corresponding url in urls.py file: from django.urls import path from . views import ..., receive_payment urlpatterns = [ ... path('receive-payment/<str:account_code>', receive_payment, name="receive-payment"), ] Thank you for lending me your time and answering my question :) -
How to send emails using RabbitMq and Django
I am new to RabbitMQ at the same time, if possible would someone also link me to a good tutorial for my task? -
How to update text area contents in django
Am trying to refresh a text area with data from a service that scans a bar code and logs the code. Am not sure what am doing wrong, I cant get the scanned data to appear on the text area. This is what I have done so far My camera stream for scanning the barcodes and logging to the console and to a list used_codes variable class CameraStream: used_codes = [] def __init__(self): self.camera = cv2.VideoCapture(int(0)) def get_frames(self): used_codes = self.used_codes while True: # Capture frame-by-frame success, frame = self.camera.read() if not success: break else: ret, buffer = cv2.imencode('.jpg', frame) # Add text on top of the barcode if there is a barcode in the stream using opencv # convert camera frame to numpy array color_image = np.asanyarray(frame) # decode numpy array to check if there is a barcode in color_image if decode(color_image): for code in decode(color_image): if code.data.decode('utf-8') not in used_codes: print('Approved. You can enter!') print(code.data.decode('utf-8')) used_codes.append(code.data.decode('utf-8')) elif code.data.decode('utf-8') in used_codes: print('Sorry, this code has been already used!') else: pass cv2.imshow('Testing-code-scan', frame) cv2.waitKey(1) return used_codes My Views getting the data from the used_codes variable and sending it to the view def detect(request): stream = CameraStream() success, frame = stream.camera.read() … -
How to Use Deep Learning model trained on GoogleColab in Django
I have Trained one text classification model using Jupyter notebook and saved model using Joblib which I easily use in django to predict ouput. Now I have trained one similar text classification on Google Colab but there am not able to use Joblib to save trained model. Also I have one doubt about how to use tokenizer used in google colab from server. If I want to predict I have to do some preprocessing on text x = ['this is a news'] x = tokenizer.texts_to_sequences(x) So, this tokenizer is fit on Trained dataset. Please let me know about this, how to save that model and use of it in django also how to preprocess the requested data. Thank You!