Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Find Hashtags in String and Replace It by Wrapping It in <a> Tag
The title is kinda long and might be confusing so let me explain. I am making a social media site, and I want to enable hashtags. For example, if a user creates a post like this: Summer is gone. #sad #comeback #summer I want to use python to replace all occurrences of # and word like this: Summer is gone. <a href="http://127.0.0.1:8000/c/sad">#sad</a> <a href="http://127.0.0.1:8000/c/comeback">#comeback</a> <a href="http://127.0.0.1:8000/c/summer">#summer</a> This is what I have so far: def clean_content(self): content = self.cleaned_data.get('content') content = profanity.censor(content) # (Unrelated Code) arr = re.findall(r"@(\w+)", content) replace_ar = [] for hsh in arr: if len(hsh) < 80: if Category.objects.filter(name__iexact=hsh): # Old Category, Added This To Category List (Unrelated Code) replace_ar.append(hsh) else: # New Category, Created Category, Then Added This To Category List (Unrelated Code) replace_ar.append(hsh) else: # Don't do anything, hashtag length too long # No Idea What To Do With replace_ar. Need help here. In the code above I take the html text input and I find all #{{word}}. I then loop through them and I check if a category exists with that name or not. If it does, I just add it to that category, and if it doesn't, I create a category and then add … -
how to update docker container automatically when i made some changes in code, without docker-compose build
when i trying to change code but container not automatically update it, it update when i run docker-compose build command this docker-compose file version: '3.8' services: backend: build: . image: app:backend container_name: backend command: 'python manage.py runserver 0.0.0.0:8000' restart: always ports: - 8000:8000 volumes: - .:/app this is docker file FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/requirements.txt COPY . /app -
Setting password for user model in the admin page
I made a costumed User model with multiple role, Customers, and Employees, where employees also are in different roles: Drivers and administration. I extended AbstractBaseUser model to set a customized user model as this: class UserAccountManager(BaseUserManager): def create_superuser(self, email, first_name, last_name, password, **other_fields): other_fields.setdefault("is_staff", True) other_fields.setdefault("is_superuser", True) other_fields.setdefault("is_active", True) other_fields.setdefault("is_driver", True) other_fields.setdefault("is_customer", True) other_fields.setdefault("is_responsable", True) if other_fields.get("is_staff") is not True: raise ValueError(_("Supperuser must be assigned to is_staff.")) if other_fields.get("is_superuser") is not True: raise ValueError(_("Superuser must be assigned to is_superuser.")) return self.create_user(email, first_name, last_name, password, **other_fields) def create_user(self, email, first_name, last_name, password, **other_fields): if not email: raise ValueError(_("You must provide an email address")) email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("Email Address"), unique=True) first_name = models.CharField(_("First Name"), max_length=150, unique=True) last_name = models.CharField(_("Last Name"), max_length=150, unique=True) mobile = models.CharField(_("Mobile Number"), max_length=150, blank=True) is_active = models.BooleanField(_("Is Active"), default=False) is_staff = models.BooleanField(_("Is Staff"), default=False) is_driver = models.BooleanField(_("Is Driver"), default=False) is_responsable = models.BooleanField(_("Is Responsable"), default=False) is_customer = models.BooleanField(_("Is Customer"), default=False) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) objects = UserAccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] class Meta: verbose_name = "Account" verbose_name_plural = "Accounts" def __str__(self): return self.first_name and … -
python syntax error on manage.py makemigrations
When I start python3 manage.py makemigration for Django for everybody course lab Week 5 Django Features and Libraries I get error: (django3) 12:01 ~/django_projects/mysite $ python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() ... File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/progroman/django_projects/mysite/mysite/settings.py", line 55 CRISPY_TEMPLATE_PACK = 'bootstrap3' ^ SyntaxError: invalid syntax settings.py code below. If I comment CRISPY_TEMPLATE_PACK = 'bootstrap3' syntax error point to TAGGIT_CASE_INSENSITIVE = True """ import os from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) APP_NAME = 'ChucksList' SECRET_KEY = 'xxxxxxxxxxxxxxxxxxx' DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', # Extensions - installed with pip3 / requirements.txt 'django_extensions', 'crispy_forms', 'rest_framework', 'social_django', 'taggit', 'home.apps.HomeConfig', 'crispy.apps.CrispyConfig', # Sample Applications - don't copy # When we get to crispy forms :) CRISPY_TEMPLATE_PACK = 'bootstrap3' # When we get to tagging TAGGIT_CASE_INSENSITIVE = True ''' Please advice what wrong in settings.py -
Django running locally on Windows Server (import error, Anaconda prompt)
I have some django web app that I just was running locally on a Windows Laptop. We need to run some tests (emphasis on the test part) and we would like to run it locally (the same way as I do on my windows laptop) on a windows server. Is it possible? Because so far I just have been encountering errors. This web app is running with anaconda and when I try to execute: python manage.py runserver I get errors that I do not get locally on my laptop, but the server has the same requirements installed (we are using python 3.8.8) and I get the following error when trying to run "locally" on the server: from . import views from . algorithms.config.parametros import * forecast_filename = f'{FILENAME_OUTPUT_BASE}.xlsx' NameError: Name 'FILENAME_OUTPUT_BASE' is not defined Ok, so a little bit of context, the second line I'm executing inside an except (that means that it failed to just execute from .parametros import * which is weird because I don't have that issue locally and apparently it can't import anything in that way). Also, I'm using Anaconda (prompt) to run this project because we are using FBProphet and one of the requirements is … -
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?