Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django navbar view changed and unstable
I supposed to have the navbar like the this. but when I first runserver with my appA, it always show the navbar like a list menu, like the figure 2. If I run another appB runserver and rerun myapp A, the navbar goes normal like figure1. So it looks like if I want to get the normal Navbar in appA, I should first run anther appB and then I can get the normal navbar for appA This is the navbar what I get if I run appA first after I open my computer. Thak you very much for any kind suggestions. It looks like the problem of static. -
Designing an intranet website using a safe Python framework
I want to develop a website using Python. This intranet website would only allow access to users internally within our company. After a quick search on suggested frameworks, I found Django, Flask and a few others. I have a question, and forgive me if I get the terminology wrong etc. My question: Is it safe to use a web framework like Django, for an internal website. My concern is that perhaps there are functions within the framework that make external calls to the greater internet. Thank in advance Garrett -
Django: Makemigration Error "models.E028" and "models.E340" after extending Authuser (legacy MySQL)
I connected my Django project to a legacy MySQL DB and did a first migration. I then extended the AuthUser model with a "NewUser" model (made sure that AUTH_USER_MODEL settings.py to reference 'appname.NewUser') When running makemigrations I get these error messages: models.E028 account_emailaddress: (models.E028) db_table 'account_emailaddress' is used by multiple models: seasonscan_api.AccountEmailaddress, account.EmailAddress. account_emailconfirmation: (models.E028) ...(same error) auth_group: (models.E028) ...(same error) auth_permission: (models.E028) ...(same error) django_admin_log: (models.E028) ...(same error) django_content_type: (models.E028) ...(same error) django_session: (models.E028) ...(same error) django_site: (models.E028) ...(same error) socialaccount_socialaccount: (models.E028) ...(same error) socialaccount_socialapp: (models.E028) ...(same error) socialaccount_socialtoken: (models.E028) ...(same error) fields.E340 auth.Group.permissions: (fields.E340) The field's intermediary table 'auth_group_permissions' clashes with the table name of 'seasonscan_api.AuthGroupPermissions'. socialaccount.SocialApp.sites: (fields.E340) ...(same error) I checked the docs which didnt show more than the error message without additional info. Any advice would help me a lot. Here the models as reference: from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db.models.signals import post_save class AuthGroup(models.Model): name = models.CharField(unique=True, max_length=150) class Meta: managed = True db_table = 'auth_group' class AuthGroupPermissions(models.Model): id = models.BigAutoField(primary_key=True) group = models.ForeignKey('AuthGroup', on_delete=models.CASCADE, related_name='authgroup_authgrouppermissions') permission = models.ForeignKey('AuthPermission', on_delete=models.CASCADE, related_name='authpermission_authgrouppermissions') class Meta: managed = True db_table = 'auth_group_permissions' unique_together = (('group', 'permission'),) … -
Django Send Mail keeps throwing WSGI error
So i was this application in which when a user fill the form, I get an email with their details so that i can contact them. But when ever the form is submitted, it shows me this error. I couldn't find whats bugging the code. All the credentials are in place. I am using SendingBlue smtp server for this project. Have a look at my code: views.py from django.shortcuts import render, redirect from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect # Create your views here. def home(request): return render(request, 'index.html') def register(request): if request.method == 'GET': return render(request, 'register.html') else: name = request.POST['full-name'] email = request.POST['email'] phone = request.POST['phone'] nationality = request.POST['nationality'] try: send_mail("Trial Application", name + email + phone + nationality, '*my email*', ['* same email*']) except BadHeaderError: return HttpResponse('Something Went Wrong') return redirect(request, 'index.html') return render(request, 'register.html') settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp-relay.sendinblue.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "*my email*" EMAIL_HOST_PASSWORD = "password" register.html <form action="" method="post" class="form"> {% csrf_token %} <fieldset> <legend>Please fill in the required details</legend> <input type="text" name="full-name" placeholder="Full Name" id=""> <input type="email" name="email" placeholder="Email" id=""> <input type="tel" name="phone" placeholder="Phone Number" id=""> <input type="text" name="nationality" placeholder="Nationality" id=""> <input type="submit" … -
Django - Adding up values in an object's many to many field?
I have 2 classes class Service(models.Model): service_name = models.CharField(max_length=15, blank=False) service_time = models.IntegerField(blank=False) class Appointment(models.Model): name = models.CharField(max_length=15) service_selected = models.ManytoManyField(Service, blank=True) total_time = models.IntegerField(null=True, blank=True) What Im trying to do is that after a user has selected the services and created an appointment, each of the services' service_time will be added up to equal total_time I know I have to use something along the lines of #in class Appointment def save(self, *args, **kwargs): self.total_time += self.service_selected.service_time #it needs to add up all of the service_time from each service selected but that's where Im lost super(Appointment, self).save(*args, **kwargs) But I don't know how to get the service_time value from each of the service_name that were selected, or how to query for every service_selected chosen in that appointment's object so that I can add up those values. -
Django: disable querysets from console
After python manage.py runserver and doing a request to the server, console displays logs of querysets for model instances for a given view. It's fine, helpful even, until trying python manage.py test, it's simply unnecessary and annoying while running tests. I've tried to disable those logs with logging.disable(logging.CRITICAL) or logging.disable() (critical is supposed to be the default value), but without any effect. I tried to put in in settings.py on condition i'm running the test environment, then i tried to make it work no matter the environment - I even tried to put it in setUp functions of test files or in test functions themselves. I also tried to modify the LOGGING variable in settings.py in various ways. Nothing worked. -
Django ORM and cursor which is better in the context of performance?
In our company there are large set of data and many db tables and we developed the backend by using Django REST and hosted in AWS and S3. Now the problem is , as a large size of data it takes too much time to fetch from the db while using Django ORM. So I need an alternative of this which provides an effective solution by faster access. So what to use incase of this? ORM/cursor/raw_sql/ or something else ? -
heroku django "file does not exist" when i try to download it from the server
I successfully deployed my app to heroku server but faced this problem when i try to download a file (like with <a href="{{object.file.url}}">Download</a>) django return "Page not found" with error "file 'app/.../.../{file}' does not exist" ("app" is not real app name. I don't know, where does it come from). Other static files (like with href="{% static "path/to/file" %}") work great. The same thing in the admin panel, when I go to the model instance, which stores the path to the file - the path is displayed, but nothing is downloaded from there. What should i do? -
'object has no attribute' when running TestCase
I´m following a django tests tutorial, but in my case the AttributeError appears from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient class RecipeImageUploadTests(TestCase): def setUP(self): self.client = APIClient() self.user = get_user_model().objects.create_user( 'user@kubousky.com', 'testpass' ) self.client.force_authenticate(self.user) self.recipe = sample_recipe(user=self.user) def tearDown(self): self.recipe.image.delete() def test_upload_image_to_recipe(self): """Test uploading an image to recipe""" url = image_upload_url(self.recipe.id) The error refers to "self.recipe" says: 'RecipeImageUploadTests' object has no attribute 'recipe' There is not much about setUP() in docs. Wonder why I can set self.user and not any other attribute -
How would I specify a data table that I have set up postgresql?
I am looking to set up the backend logic for a form where it shoots information to a data table that I set up in postgresql and was wondering, how I would specify the data table that I want to send the information to? -
is there any way to get Django to read react components?
i am trying to import my react project to Django. I set up webpack, babel and finally all the backend ... But when I tried to import React's 'index.js' file it reads it successfully but fails to write it into the page's DOM. I tried testing the file without React and everything works fine, however, does anyone know how to give me some advice? -
Django views with SSE and external scripts
If there is a better way to accomplish this, please let me know. I need to synchronously process data outside of a view, then only after data is processed in an external function redirect or open a new view. File is uploaded from an HTML page, which routes the file to views. Threading in views begins processing data in script outside of views. Views returns a view to display the data as it's being processed using SSE. External script sends data using send_event('test', 'message',{'text': stuff} Here's where I'm stuck: I've tried using the Javascript event listener to watch for certain text that then does a window.open('newview'), as I have a view that downloads the CSV the script creates. I'm having a problem going from one view (with an active SSE connection) to another while waiting on the thread that is processing data to finish. I've tried a second thread in views.py that returns another response when thread x is finished. I have to return render from the first view so that the live data shows to the client. Html for upload: <form action="/viewFunction/" method="POST" enctype="multipart/form-data" form target="_blank"> {% csrf_token %} <input type="file" id="fileform" name="filename"> <input type="submit" id="fileform"> views.py: def viewFunction(request): … -
Using inlineformset_factory getting incorrect id's from foreign key
I'm trying to use inlineformset_factory to generate a series of number boxes within a table to update the additional field in a through table from a self referential many-to-many relationship. views.py def edit_assembly(request, slug): root = Part.objects.get(slug=slug) forms = inlineformset_factory(Part, Relationship, fields=('qty',), fk_name="child", can_delete=False) if request.method == 'POST': formset = forms(request.POST) if formset.is_valid(): formset.save() else: formset = forms(instance=root) return render(request, "app/edit_assembly.html", { "formset": formset }) models.py class Part(models.Model): part_number = models.IntegerField() slug = models.SlugField(unique=True) name = models.CharField(max_length=40) children = models.ManyToManyField( 'self', symmetrical=False, through='Relationship', through_fields=('parent', 'child'), blank=True) class Relationship(models.Model): qty = models.IntegerField(default=1) parent = models.ForeignKey( Part, on_delete=models.CASCADE, related_name='parent', null=True) child = models.ForeignKey( Part, on_delete=models.CASCADE, related_name='child', null=True) template: <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} <br> {% endfor %} <input type="submit" value="Submit"> </form> Whatever I try I cannot seem to return a valid form. When I look at the page source with my browser the ID's that are assigned to the hidden fields in each form are not what I would expect. currently am experiencing the error: "(Hidden field child) The inline value did not match the parent instance." I suspect the hidden field child should contain the foreign key for the … -
Override create method
New to drf.I have json input data like below: { "name":"df", "email":"d@gmail.com", "age":"21", "gender":"Male", "phone":"234", "total_price":86, "advance":0, "due":86, "selected":[{"id":8,"name":"sdf","price":34},{"id":9,"name":"dg","price":52}] } Below is my views.py.I want to override create method for the json input data.But no idea how to do it. class PatientEntry(generics.CreateAPIView): queryset = Test.objects.all() serializer_class = PatientSerializer def create(self, request, *args, **kwargs): many = isinstance(request.data, list) serializer = self.get_serializer(data=request.data,many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, headers=headers) -
cod=H10 'App crashed' when trying to deploy to Heroku
I've been trying to deploy an app to Heroku, but can't get past the following errors (appear when I run heroku logs --tail). These are the errors: ModuleNotFoundError: No module named 'app-name' Process exited with status 3 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" My files structure looks like this: frontend (React app) package.json static templates website (Django app) manage.py package.json Procfile requirements.txt My Procfile looks like this: release: python manage.py migrate web: gunicorn app-name.wsgi --log-file - -
django.db.utils.ProgrammingError: column "organisation_id" of relation "notification_notification" already exists - Django on Heroku Deployment
I seem to be getting the following error when I am deploying to Heroku, i've tried to do --fake but it breaks the application and gives a 500 error when you sign up as it does not have an organisation id which is used as a UID. Any tips on what i can do to stop this happening? Operations to perform: Apply all migrations: account, admin, auth, blog, chat, contenttypes, customform, integration, licence, location, maintenance, member, notification, organisation, registry, report, risk, sessions, sites, socialaccount Running migrations: Applying notification.0010_auto_20210429_0032...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.DuplicateColumn: column "organisation_id" of relation "notification_notification" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, … -
How to accelerate Django mysql queries to show in datatables?
I am developing a website with Django and i have about 500 object for now. It takes page 2 seconds to load and display in datatables. I show 10 objects with 50 pages in jquery datatables. However, the data may get bigger as the time goes by. What should i do to prevent website crushing or not loading at all. Any help is appreciated. Thanks. -
Django How to UPDATE ... RETURNING
In Postgresql you can issue an UPDATE with a RETURNING statement in order to fetch some columns after you perform an update. This is useful because you can do this in one trip to the database instead of two. UPDATE foo SET bar = 10 WHERE id = 1 RETURNING baz How can I simulate this in Django without using a raw query ? I have seen some older questions on stackoverflow from a few years ago indicating this was not possible. Has anything changed in recent years? I do not want to do the following, which requires two trips to the database: foo = Foo.objects.get(id=1) foo.bar = 10 foo.save() print(foo.baz) I did see this ticket from four years ago which was rejected. Has anything changed? -
django admin 404 page display error. Unable to find return page when data is inserted
when I add or delete data in the admin, I get 404 not found error. I am using windows server. Error: urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.contrib.sitemaps.views import sitemap from home.sitemap import StaticViewSitemap sitemaps = { 'static':StaticViewSitemap } urlpatterns = [ path('admin/', admin.site.urls), path('', include("home.urls"), name="anasayfa"), path('sitemap.xml', sitemap, {"sitemaps":sitemaps}, name="sitemaps") ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Home urls.py: from django.contrib import admin from django.urls import path from django.views.generic import TemplateView from . import views app_name = "home" urlpatterns = [ path(r'', views.index, name="anasayfa") path(r'galeri', views.galeri, name="galeri"), ] models.py from django.db import models class Galeri(models.Model): baslik = models.CharField(max_length=255,null=True,blank=True, verbose_name="Başlık") resim = models.ImageField(blank=True, null=True, verbose_name="Fotoğraf Ekle") class Video(models.Model): baslik = models.CharField(max_length=255, null=True, blank=True, verbose_name="Başlık") video = models.FileField(upload_to="video", blank=True, null=True) settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "home", 'django.contrib.sitemaps' ] The project was working fine in localhost, but I have such a problem when I upload it to my domain address. The pages of the site are working fine, but there is only this problem in the admin panel. I'm sorry for my bad english. Thanks in advance for your help -
How do I call a Django function without button click
How do I call a Django function without button click.. I want to pass a variable value from views.py & i need to use in template language without forms. -
How do I run a loop in Django while server is working as usual?
I am trying to create a csgo trading website where the users can withdraw and deposit skins. To do so I have created a bot account that sends trading offers to the customer. Now I need to somehow confirm that the trade was accepted by the user. I am new to this so there might be a better, simple solution that I just can't figure out. I am using steampy library. What I think would be the solution is to run a function loop that checks for the offers and their state. And on state change would update the database. But I do not know how I can create a function like this in Django so the server would also be running at the same time. I want to also use this project in production so running a script from my computer isn't the solution. Can someone please help me with the issue or lead me in the right direction? -
How can I make a carousel in a bustrap
The task is that the user creates cards. These cards must be placed in the gallery. When scrolling, a gallery of these cards is created. Tell me how to do it Html <div id="gallery" class="carousel slide carousel-fade" data-ride="carousel" data-aos="fade-up" data-aos-delay="300"> <div class="carousel-inner"> {% for el in tasks %} <div class="carousel-item active" data-interval="100"> <h5>{{ el.title }}</h5> </div> {% endfor %} </div> -
Reading CSV from Django model, No such file or directory
FileNotFoundError: [Errno 2] No such file or directory: 'static/data/cleanHeart.csv I receive this error when attempting to access my csv file in my models.py file within a model named Patient and a method named perform_prediction. My intent is to, with the use of some attributes available within Patient, to generate a prediction with the help of the data. def perform_prediction(self): main_df = pd.read_csv('static/data/cleanHeart.csv') regu = linReg.fit(main_df[['Age','Sex', 'ChestPainType', 'RestingBP', 'Cholesterol', 'FastingBS', 'RestingECG', 'MaxHR', 'ExerciseAngina', 'Oldpeak', 'ST_Slope']],main_df['HeartDisease']) tester = regu.predict([[65,0,3,140,306,1,0,87,1,1.5,0]]) return tester To ensure my relative path is correct, I created an acceptablepath.py in the exact same location with the method code, and was successfully able to access cleanHeart.csv. I am calling this function from a template. To ensure that was not the issue, I created a simple ping_me method which has no problems returning to the template. def ping_me(self): return 'ping!' Is this issue related to the settings.py in anyway? I even placed the cleanHeart.csv in the same directory with models.py and I still am unable to access it. There are no pending migrations. -
Edit Many To Many Field in Django
I am having a problem in editing a page in my code. Basically I have a page where I have multiple select field where I can select the students. But I have a problem in understanding how to remove a specific student, if I need to edit this page. Let me be more clear with some code. models.py class TheorySyllabus(models.Model): name = models.CharField(max_length=100, null=True, blank=True) subject_duration = models.ManyToManyField( SubjectDuration, related_name='theory_syllabus') course_type = models.ForeignKey( CourseType, on_delete=models.DO_NOTHING, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: verbose_name_plural = 'Theory Syllabus' class TheoryCourse(models.Model): name = models.CharField(max_length=100) student = models.ManyToManyField(Student, related_name='theory_courses') theory_syllabus = models.ForeignKey( TheorySyllabus, on_delete=models.DO_NOTHING, null=True, blank=True) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name views.py def edit_theory_course(request, pk): theory_course = TheoryCourse.objects.get(id=pk) student_obj = theory_course.student.all() theory_syllabus = TheorySyllabus.objects.all() students = Student.objects.filter(is_active=True).order_by('last_name') context = { 'theory_course': theory_course, 'theory_syllabus': theory_syllabus, 'students': students, 'student_obj': student_obj, } if request.method == 'POST': course_name = request.POST.get('course_name') student = request.POST.getlist('student') syllabus = request.POST.get('syllabus') try: theory_course.name = course_name theory_course.theory_syllabus_id = syllabus theory_course.save() for stud in student: theory_course.student.add(stud) theory_course.save() messages.success(request, "Theoretical Course Edited") return HttpResponseRedirect(reverse('theory:course_list')) except: messages.error(request, "Failed to Edit Theoretical Course") return HttpResponseRedirect(reverse('theory:edit_theory_course', kwargs={'pk': pk})) return render(request, 'theory/edit_theory_course.html', context) I know … -
How to solve "Exception Value 'UserRegistrationModel' instance expected, got <User: admin>" error in my django project?
So in my django project i have this friend request system, it works for the most part (i think), i can send friend requests and then those respective users actually recieve the friend request, but when i try to accept that friend request it shows this error:error these is my views.py( the views i use in the friend request system have friends or something in their name, everything else is for other staff) from django.shortcuts import render from django.contrib.auth.decorators import login_required from .forms import UserRegistration, UserEditForm,PostForm from django.views import generic from .models import Post,Friend_Request from django.contrib.auth.models import User # Create your views here. def friends(request): users = User.objects.all() return render(request, 'authapp/friendrequest.html', {'allusers':users}) def friends_accept(request): all_friend_requests = Friend_Request.objects.all() current_user = request.user to_user = User.objects.get(id = current_user.id) all_friend_requests = Friend_Request.objects.filter(to_user = to_user) return render(request, 'authapp/friends_request.html', {'all_friend_requests':all_friend_requests}) def download(request): context = { "welcome": "Welcome to your dashboard" } return render(request, 'authapp/download.html', context=context) def index(request): queryset = Post.objects.all() context= {'post': queryset} return render(request, "authapp/post.html", context) def blogs(request): posts = Post.objects.all() posts = Post.objects.filter().order_by('-created_on') return render(request, "authapp/post.html", {'posts':posts}) class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'authapp/post.html' class PostDetail(generic.DetailView): model = Post template_name = 'authapp/post_detail.html' @login_required def send_friends_request(request,userID): from_user = request.user to_user = User.objects.get(id = userID) …