Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Why am i getting the An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block
So i've been cracking on this issue for days now and i do not seem to get closer to a fix. I currently have two models. A PurchaseOrder (PO) model and a PurchaseOrderLine (POL) model. The POL models has a foreignkey to PO. I upload a CSV and using pandas i'm reading through each line of the csv and parsing it accordingly. First it tries to do an PO.objects.get_or_create() based on the values in the row. Using that created PO, i do some logic and basically end up creating a POL instance that i want to link to the earlier mentioned PO instance. However, when creating the POL, i get a: TransactionManagementError An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. And i do not understand why that is. I have similar logic in my code elsewhere, for example creating a Order and then adding OrderLines to that Order. Any ideas what i'm doing wrong here? See below all code relevant (i removed some logic about settings values etc). The error is thrown at the final block where the POL is created using the get_or_create(). @classmethod def parse_purchase_order_from_csv(cls, purchase_file, store_id, supplier_id=0, … -
Django - id of inserted object in class based generic create view
I'm using generic Create view in Django for user signup: from django.shortcuts import render, redirect, reverse from django.views import generic from .forms import CustomUserCreationForm class SignupView(generic.CreateView): template_name = "registration/signup.html" form_class = CustomUserCreationForm def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.send_email() return super().form_valid(form) def get_success_url(self): return reverse ("login") In form_valid method I need to pass created user id to send_mail like this: form.send_email(user) In function view, I would just use: user = form.save(commit=False) and later access user.pk How can I do this in class based view? -
Field 'id' expected a number but got (<Group: STUDENT>, False)
I have a registration form where I want to register a student and instantiatee a Student model and add them to that model. I have a CustomUser model which is referenced by the Student model. CustomUser model class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) phone = models.CharField(max_length=150, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) profile_picture = models.ImageField(default='images/student.png', upload_to='profile_picture/', null=True, blank=True) is_student = models.BooleanField(default=False) is_moderator = models.BooleanField(default=False) is_administrator = models.BooleanField(default=False) def __str__(self): return self.get_username() Student model class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) @property def get_instance(self): return self def __str__(self): return self.user.username views.py from django.contrib.auth.models import Group from student.models import Student from quiz.forms import RegistrationForm def register_student_view(request): form = RegistrationForm() if request.method == 'POST': form = RegistrationForm(request.POST, request.FILES) if form.is_valid(): user = form.save(commit=False) user.is_student = True user.save() student = Student.objects.create(user=user) student_group = Group.objects.get_or_create(name='STUDENT') student.user.groups.add(student_group) messages.success(request, 'Registration successful!') return redirect('login') form = RegistrationForm() return render(request, 'accounts/register.html', {'form': form }) I don't want to directly use the CustomUser and call users directly from it. Instead of calling a user from the CustomUser, I want the user to be in the Student model which has a foreign key to the CustomUser, and then I can do my business logic with the Student instance -
How to fetch particular fileds alone in django?
I have two models Model Faculty & Model Courses. The concept is as follows, when a new course is created user need to select respecitive faculty. As of now there isnt any relation between faculty and course, am just using faculty as ModelChoiceField to show available dropdown and save a course ! The problem is, i need to show available course in faculty wise like the below: So the above can be achived using relationships i belive, my question is when i show the courses faculty wise i need to fetch all the courses and its contents along with faculty and only show course name and faculty name ! But to show only course & faculty name am fetching all the course details which is waste ! How to tackle this ? Option1: One to Many relation between faculty and course and then store all the course name in faculty (so that i can directly show only course name ) & Option2: One to One relation with Course and Faculty,. Now Fetch all the course contents and show both faculty and course name alone ( this will have plenty of waste data as it has tons of information ) Is … -
During 2 days I was working to deploy a django app with heroku but I couldn't do. Could anyone do that and explain me where I was doing mistake?
I created a django app which is converting and downloading mp3 musics from youtube. I was working to deploy it from heroku but I couldn't do it. It is woking fine on local machine but I can't deploy it. Could anyone deploy it and say me my mistake. You can reach the source code from https://github.com/harunkara/django-mp3-downloader. You can download my source code and you can deploy it and tell me where I was doing mistake. Two days without sleep, I want to know I couldn't do that? -
Can't get form data from site to save in database Django MySQL
I am using Django with MySQL database. Everything is working, but the data I input will not save to the database. This is my HTML: <label for="project-name" class="block text-sm font-medium text-gray-700"> Project Name </label> <div class="mt-1"> <input type="text" name="project-name" id="project-name" autocomplete="given-name" class="shadow-sm focus:ring-gray-500 focus:border-gray-500 block w-full sm:text-sm border-gray-300 rounded-md"> </div> This is my views.py def project(request): if request.method == 'POST': form = ProjectForm(request.POST or None) if form.is_valid(): form.save() all_items = Project.objects.all return render(request, 'project.html', {'all_items': all_items}) all_items = Project.objects.all return render(request, 'project.html', {'all_items': all_items}) This is my forms.py: class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['project_name', 'project_location', 'operator', 'date_started'] I am not getting any errors, but the data I save is not saved in the database. Can anyone see what I need to fix? -
How to apply user specific list?
I am new in Python Django.I have a question in one situation.As you see in the photos,I have an application.Firstly Users can login system and they can add new item to list.Problem is that when all users login,they are adding items to the same database.For example when 2 users login,they will see same items.I want apply specific list for each user.When each user login,they should see their own list.I know that I have to apply one to many relationship but I don't know how can I do this.I need to know which codes should I write in views.py (in def add(request) . How we see application) note: my item's model name is Student models.py from django.db import models from django.contrib.auth.models import User from django.db.models.base import Model from django.db.models.deletion import CASCADE class Student(models.Model): sid=models.CharField(max_length=7) sname=models.CharField(max_length=255) scontact=models.CharField(max_length=15) user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="todolist", null=True) def __str__(self): return self.sname class ExtendUser(models.Model): r = models.OneToOneField(User,on_delete=models.CASCADE) date_of_birth = models.DateField(null=True) city = models.CharField(max_length=30) def __str__(self): return self.r.username views.py from django.shortcuts import render,redirect from .forms import StudentForm from django.http import HttpResponseRedirect from .models import Student from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required # Create your views here. def add(request): form=StudentForm(request.POST or None) if form.is_valid(): # I know ,I … -
Unable to Upload Image to Media Django
I have faced some problems to upload the image in Django. After I submit the form, the image URL is successfully inserted to the database but there is no image created to the media file. Can you guys please help me to find where is the problem. Thank you. Here is the code. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR,'static/images/') models.py class Image(models.Model): img = models.ImageField(upload_to='testing') views.py def goProfile(request): if request.method == "POST": image = Image( img = request.POST.get('imgTest') ) image.save() return render(request,'profile.html') profile.html <form action="" method="post"> {% csrf_token %} <input type="file" name="imgTest" id="imgTest"> <input type="submit" value="submit"> </form> -
How to deserialize XML text created by Django framework in C#
I am trying to deserialize a XML text in C# in Xamarin.Forms. Text is coming from Django Rest API framework and dynamically serialized to XML by django as you can see sample below. I want deserialize this text in C# in Xamarin.Forms. I want to get something like below. [country,totaldata,usage] [CH,3342440,536] [UK,705645,479] Sample XML is : <django-objects version=\"1.0\"> <object model=\"APP.backuplocation\" pk=\"1\"> <field name=\"country\" type=\"CharField\">CH</field> <field name=\"totaldata\" type=\"IntegerField\">3342440</field> <field name=\"totaldisk\" type=\"IntegerField\">423940</field> <field name=\"useddisk\" type=\"IntegerField\">23856</field> <field name=\"freedisk\" type=\"IntegerField\">19024</field> <field name=\"usage\" type=\"IntegerField\">536</field> <field name=\"avg\" type=\"FloatField\">16.0</field> </object> <object model=\"APP.backuplocation\" pk=\"2\"> <field name=\"country\" type=\"CharField\">UK</field> <field name=\"totaldata\" type=\"IntegerField\">705645</field> <field name=\"totaldisk\" type=\"IntegerField\">136547</field> <field name=\"useddisk\" type=\"IntegerField\">6770</field> <field name=\"freedisk\" type=\"IntegerField\">6897</field> <field name=\"usage\" type=\"IntegerField\">479</field> <field name=\"avg\" type=\"FloatField\">11.0</field> </object> </django-objects> -
How can I retrieve a list of dictionary value as output using annotate in Django?
While I am working on the creation of API questions and answers by categories. I'm able to count the number of users who chose different options. Now, I'm stuck on retrieving the user's data who chose that option. I can achieve this using for loop on options data and get all the user's data. But the number query generates for this method is huge in numbers. Is there any way that we can do it using annotate? models.py class Question(models.Model): institute = models.ForeignKey('Institute', on_delete=models.CASCADE, related_name='questions', null=True, blank=True) question = models.TextField() category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True, related_name='questions') subject = models.ForeignKey('TrnSchoolSubject', on_delete=models.CASCADE, null=True, blank=True, related_name='questions') for_institute = models.BooleanField(default=True) difficulty = models.ForeignKey(Difficulty, on_delete=models.CASCADE, null=True, blank=True) is_active = models.BooleanField(default=True) is_survey = models.BooleanField(default=False) **Question options** class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') text = models.TextField(null=True, blank=True) is_correct = models.BooleanField(default=False) sequence = models.IntegerField(default=0) class AnswerTracking(models.Model): student = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="answer_tracking") category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name="question_category") question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="tracking_question") student_answer = models.ForeignKey(Answer, on_delete=models.CASCADE, null=True, related_name="student_answer") answer = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name="correct_answer") views.py @api_view(["GET"]) def admin_faq_category(request, category_id): questions = (Question.objects .prefetch_related("answers") .annotate(total_users=Count("tracking_question")) .filter(is_active=True, for_institute=True, category_id=category_id, institute=request.user.institute ) .values("id", "question", "is_active", "for_institute", "is_survey", "marks", "negative_marks", "total_users") .order_by("id") ) for question in questions: answers = (Answer.objects.filter(question__id=question["id"]) .prefetch_related("student_answer") .annotate(vote=Count("student_answer"), … -
Django React CORS
I already installed django-cors-header and set up my settings.py in this way: ALLOWED_HOSTS = [ 'http://localhost:3000', 'localhost' ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000" ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "corsheaders", 'rest_framework', 'rest_framework_simplejwt', 'service_get_data', 'background_task', 'service_append_data', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and yet when I do a GET request I get this error: Access to XMLHttpRequest at 'http://localhost:8000/login/csrf/' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. here is the GET request: axios.get('http://localhost:8000/login/csrf/', {withCredentials: true}); and the Django View: from django.middleware.csrf import get_token from rest_framework.response import Response class CsrfAPI(APIView): def get(self, request): response = Response({"message": "Set CSRF cookie"}) response["X-CSRFToken"] = get_token(request) return response Also here is the response headers: Access-Control-Allow-Origin: http://localhost:3000 Allow: GET, HEAD, OPTIONS Content-Length: 29 Content-Type: application/json Date: Mon, 06 Sep 2021 10:56:59 GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.7.7 Set-Cookie: csrftoken=Exx4Qdt7aYP78EajkglHKwJ3O7rCcU8qp6dIvuLu070z8IYaaH8XQDmDzOhDqWn1; expires=Mon, 05 Sep 2022 10:56:59 GMT; Max-Age=31449600; Path=/; SameSite=Lax Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-CSRFToken: PMW2N3vIqWS3QMmYafE008DMAnVbQrpWAlCGskN5g53vQQaP0Grg6fgml4Lc4tEx … -
Django Rest Framework + Simple JWT - Retrieve saved refresh token from access token?
I am trying to retrieve the pair Access/Refresh token using the access token as the input. Since I'm using the JWT Blacklist, I figured out that I can easily retrieve a list of all refresh tokens by a user id (which I can decode from the access token), but I could not find a way to retrieve the Refresh token that was generated for this specific access token. Any ideas? -
Django-Debug-Toolbar not showing(disallowed MIME type)
i install django-debug-toolbar 3.2.2 and configure it step by step by Installation Django Debug Toolbar my templates is just hello.html <html> <body> <h1>Hello {{ name }}</h1> </body> </html> at the end, when i type python manage.py runserver Django Debug Toolbar not show up. but in concole i see this Loading module from “http://127.0.0.1:8000/static/debug_toolbar/js/toolbar.js” was blocked because of a disallowed MIME type (“text/plain”). python 3.8.8(base on anaconda) Django 3.2.7 windows 10 what's going on? -
Django 3.2 how to redirect 404 to homepage
I did find a number of answers about 404 redirect for Django but mostly are referring to an older version of Django. Here is what I have in Django 3.2.6 DEBUG is set to False to trigger the 404 behaviour urls.py handler404 = views.view_404 views.py def view_404(request, exception=None): return HttpResponseRedirect("/") No error in runserver but a 404 page still returns "Not Found The requested resource was not found on this server.". -
Status disappear if updated while scripts is running (read and write simultaneously doesn't happen)
While this script runs if any product is marked critical then it doesn't get updated instead reset back to not critical so, how to perform read and write operation simultaneously? def get_latest_comment_from_xsite( curs, how_far_back ): print "starting app get latest comment after %0.2f seconds" % ( time.time() - start ) # minutes_back = 24*60 print "Going back %0.2f minutes" % (how_far_back) sql = """ WITH ORDERED AS ( SELECT eh.equipmentname, to_date(eh.time,'YYYYMMDD HH24MISS\"000\"') AS \"TIME\", NVL(eh.workordernumber,eh.workrequestnumber ) AS \"WORKORDERNUMBER\", eh.username, DBMS_LOB.SUBSTR(ec.detaildescription,1700,1) AS \"COMMENTTEXT\", ROW_NUMBER() OVER (PARTITION BY eh.equipmentname ORDER BY eh.equipmentname ASC) AS rn FROM FwEqpHistory eh, FwEqpComment ec WHERE ec.sysId (+) = eh.eqpComment AND ec.detaildescription NOT LIKE 'Marked as critical%' AND ec.detaildescription NOT LIKE 'Removed from critical%' AND eh.time > TO_CHAR(sysdate - {0}*((1.0/24.0)/60.0),'YYYYMMDD HH24MISS')||'000' ORDER BY 1, 2 desc) SELECT * FROM ORDERED WHERE rn = 1""".format(how_far_back) print sql curs.execute(str(sql)) comments = curs.fetchall() print "Collected app Data after %0.2f seconds" % ( time.time() - start ) for row in comments: tool_id, comment_time, wo_number, user_id, comment_text, row_num = row print tool_id + ' ' + str( comment_time) + ' ' + user_id + ' ' + comment_text try: status = CurrentStatus.objects.get(table_name = tool_id) if ( status.title_updated_at == None or status.title_updated_at < … -
How to deploy react-django project with a react app inside the django api?
I have a django app with two django apps inside it, one is an api and other is a frontend app which has a react app made inside it. How do I deploy it to heroku? If I specify a buildpack that includes nodejs, the package.json is not in the root directory [it's inside the child django app]. I tired just copying out the child django app and pasting it in root directory. But it gives this error: Field 'browser' doesn't contain a valid alias configuration -
How delete column in database [Django]
hi i'm working on a project with django but i'm having some problem in deleting 2 columns from the table. I deleted the columns in question in the initial.py and models.py files. Then when I execute the command "python manage.py makemigrations" the terminal replies in this way: File "C: \ Users \ Marco \ AppData \ Local \ Programs \ Python \ Python39 \ lib \ site-packages \ django \ urls \ conf.py", line 34, in include urlconf_module = import_module (urlconf_module) File "C: \ Users \ Marco \ AppData \ Local \ Programs \ Python \ Python39 \ lib \ importlib \ __ init__.py", line 127, in import_module return _bootstrap._gcd_import (name [level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C: \ Users \ Marco \ Desktop \ REAL4 \ ecomapp \ urls.py", line 2, in <module> from .views import * File "C: \ Users \ Marco \ Desktop \ REAL4 \ ecomapp \ views.py", line 12, in <module> from .forms import * … -
GIS - Can i have multple geo_fields (point, polygon, line) in 1 model and then serialize with DRF?
If I have 1 model with 3 different geo_fields in (point, poly and line), can I serialize all of these with django-rest-framework-gis? My model: class Job(BaseModel): name = models.CharField(max_length=64) desc = models.CharField(max_length=64) loc_poly = models.PolygonField(blank=True) loc_polyline = models.LineStringField(blank=True) loc_point = models.PointField(blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) Can I serialize by doing something like: class JobSerializer(GeoFeatureModelSerializer): class Meta: model = Job geo_field = ("loc_point", "loc_polyline", "loc_poly") fields = ('__all__',) Basically can I have geo_field to be multiple geo fields? Or is this only 1? -
Django cms not updating the page type
I am trying to create the Page Type and use it in the pages, and I can create it and use it in the pages at the time of creating the pages. But after the creation of the Page, I cant update the Page Type. -
Celery task and python function debug together
I have a Test class in the SampleFIle.py file that looks like this: Class Test: def m1(): import ipdb; ipdb.set_trace(); # Some logic In the same file I have a celery task that looks like this: @shared_task() def m1_task(): from celery.contrib import rdb rdb.set_trace() # some logic But The rdb break after the function returns. It doesn't go and checks what m1() contains. How can I debug both celery tasks and related functions for a better understanding of coding flow? -
I need has_perm() example for AbstractBaseUser in django
I have a Custom User Model, and I need to give permissions to users with certain roles (fields in user model) but I couldn't find any examples on the internet, so I'm asking for examples from anybody who has done this before. Here's my Abstract user model for reference: class User(AbstractBaseUser, PermissionsMixin): class RoleChoices(models.TextChoices): admin = 'Admin', _('Admin') cashier = 'Cashier', _('Cashier') waiter = 'Waiter', _('Waiter') courier = 'Courier', _('Courier') customer = 'Customer', _('Customer') username = models.CharField(_('username'), unique=True, max_length=100) name = models.CharField(_('name'), max_length=100) surname = models.CharField(_('surname'), max_length=100) phone_number = models.CharField(_('phone_number'), max_length=100, null=True, default='Invalid Phone Number') role = models.CharField(max_length=50, choices=RoleChoices.choices, default=RoleChoices.customer) active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['name', 'surname'] class Meta: ordering = ['date_joined', ] def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_active(self): return self.active objects = CustomUserManager() Thanks in advance, and Please excuse any grammatical errors. -
Error Apollo Client local resolver handling has been disabled and 400 Bad Request
I use GraphQl to access and set JWT token into Authorization Header, but it issues 2 errors, i have done every thing but I cannot resolve and fix it. const client = new ApolloClient({ uri: "http://localhost:8000/graphql/", fetchOptions : { credentials: "include" }, request: operation => { const token = localStorage.getItem('authToken') || ""; operation.setContext({ headers: { Authorization: `JWT ${token}` } }); }, clientState : { defaults: { isLoggedIn: !!localStorage.getItem('authToken') } } }); Dev tools warning that: Found @client directives in a query but no ApolloClient resolvers were specified. This means ApolloClient local resolver handling has been disabled, and @client directives will be passed through to your link chain. POST http://localhost:8000/graphql/ 400 (Bad Request) -
Why {{ form }} represents a form instance in template file?
According to django official doc, All you need to do to get your form into a template is to place the form instance into the template context. So if your form is called form in the context, {{ form }} will render its <label> and <input> elements appropriately. Where is the form instance named/defined as form for template context in django source code? and How can I change the name to something else {{ my_form }} for example ? -
Django - Get urls of all images that reference a Post?
I have this model where a Post can have many Photos. I'm trying to retrieve all posts, including ImageField url attribute (according to Django docs FileField and ImageField have a url attribute). So I'd like to ideally return all the urls of the images associated with the post (ideally in order of created). model.py class Post(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_id") goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = models.ManyToManyField(HashTag) class Photo(AbstractBaseModel): created = models.DateTimeField('Created at', auto_now_add=True) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=directory_path) view.py def get(self, request): data = Post.objects.order_by('created').values('body', 'goal_id__description', 'created', 'creator_id__username', replies=Count('replypost'), cheers=Count('cheerpost'), image_urls='photo__image_url') return Response(list(data), status=status.HTTP_200_OK) -
how to use django Serializer to update an instance
in Django PUT method, I want to update an instance: sv= SV.objects.get(pk=pk) serializer = SVSerializer(sv, data=request.data) if serializer.is_valid(): Here, in request.data, I just want to pass some of the variable of SV. But as some fields missing, the is_vaild will be false. What I want is, just update the fields in request.data, for the other ones, keep the value in sv. How could I do that?