Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Guys, there is a problem with template. My task is create a fliter in dropdown menu and last problem in templates
My models: class Category(ModelWithSlugMixin): class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' slugifying_field_name = 'title' title = models.CharField(verbose_name='Наименование', null=True, max_length=255) slug = models.SlugField(verbose_name='Slug', unique=True, null=True, blank=True, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('article:category', kwargs={'category_slug': self.slug}) class Article(ModelWithSlugMixin): class Meta: verbose_name = 'Статья' verbose_name_plural = 'Статьи' slugifying_field_name = 'title' category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name='category', blank=False, null=True) title = models.CharField(verbose_name='Заголовок', max_length=255, null=True) slug = models.SlugField(verbose_name='Slug', unique=True, null=True, blank=True, unique_for_date='publish') text = RichTextUploadingField(verbose_name='Текст', null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles') publish = models.DateTimeField(default=timezone.now) created_at = models.DateField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('article:article-detail', kwargs={'slug': self.slug} My view: class ArticleView(ListView): model = Article template_name = 'pages/analysis.html' context_object_name = 'articles' queryset = Article.objects.all() def get_context_data(self, **kwargs): context = super(ArticleView, self).get_context_data(**kwargs) # context['category'] = Category.objects.all() context['article_image'] = Photo.objects.all() context['article_pictures'] = Collage.objects.all() context['article_videos'] = Video.objects.all() return context class ArticleCategoryView(ListView): model = Article template_name = 'pages/analysis.html' context_object_name = 'articles' def get_queryset(self): return Article.objects.filter(category__slug=self.kwargs['category_slug']) def get_context_data(self, **kwargs): context = super(ArticleCategoryView, self).get_context_data(**kwargs) context['cat_selected'] = context['articles'][0].category_id return context Mu url: path('category/<slug:category_slug>/', ArticleCategoryView.as_view(), name='category'), And finally my template structure: <h3 class="widget-title">Categories</h3> <div class="form-group select-group"> <label for="category" class="sr-only">Select Category</label> <select id="category" name="category" class="choice empty form-control"> <option value="" disabled="" selected="" data-default="">Выбери категорию </option> <option>First category</option> <option>Second category</option> <option>Third category</option> … -
query set in django
i really need help with this: I have 3 models say User,Item and Comment where User is a foreign key in Item and Item is a foreign key in Comment. i want to get all comment belonging to a particular user in my view, how do i achieve it. bellow is are my model class User(models.Model): name= models.CharField(max_length=200,null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Item(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) name= models.CharField(max_length=200,null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Comment(models.Model): user = models.ForeignKey(Item, on_delete=CASCADE) name= models.CharField(max_length=200,null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
Why the login_requried decorator doesn't work after I login to an account?
Working on a project using Django 3.2, I have been added new features to the project by adding a login/register page for the user. To do that, I used which I used this library provided by Django from django.contrib.auth.models import User, and as well in the views I used from django.contrib.auth import authenticate, login, logout library. After I finished the login/register successfully I decided to do the authenticate the home page for the reason that the user without an account can't have access to the home page. To do that I used the decorators from django.contrib.auth.decorators import login_required, and I used it on every view that I want to authenticate for the unregistered user. To understand it better will show the code below: views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) @login_required(login_url='login/') def … -
django-cloudinary-storage must supply api_key
I'm using django-3.2.6, django-cloudinary-storage-0.3.0 and python-3.9.7 earlier the cloudinary was detecting API_KEY, but I don't know what happened now. settings.py DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get("CLOUD_NAME"), 'API_KEY' : os.environ.get("CLOUDINARY_API_KEY"), 'API_SECRET': os.environ.get("CLOUDINARY_API_SECRET"), } I tried to print the values i passed on CLOUDINARY_STORAGE, and it loads all .env succesfully, but django_cloudinary_storage isn't detecting these variables logs Environment: Request Method: POST Request URL: http://localhost:8000/admin/api/news/add/ Django Version: 3.2.6 Python Version: 3.9.7 Installed Applications: ['whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'api.accounts', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django_filters', 'taggit', 'drf_yasg2', 'corsheaders', 'cloudinary', 'cloudinary_storage'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1657, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/options.py", … -
i am getting a hard time to impement two factor authentication using the totp ,i want the user after normal login to be prompted the token login page
the function bellow is the one i was trying to implement the logic behind the two factor authentication ''' def login_view(request): if request.user.is_authenticated: return redirect('/dashboard') if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] cache.set('email',email) fact = User.objects.filter(email=email).values('username') username = fact[0]['username'] username = username.encode(encoding='utf-8') password = password.encode(encoding='utf-8) username = username.strip(b"b'") print(username) print(str(password)) user = authenticate(request, username=username, password=password) cache.set('user',user) if user is None: context = {'error':'incorrect username or password'} return render(request, 'index.html' , context) print(username) is_enrolled = enrolled(request) if not is_enrolled.json(): login(request, user) return redirect('/dashboard') return render(request, 'tokenlogin.html') return render(request, 'index.html') ''' also the function below i wrote to check if the user has enrolled for two factor authentication ''' def isenrolled(request): email = request.user.email res = requests.post( 'http://0.0.0.0:8000/api/users/email/', data={ 'account_name': email, }, headers={ 'Authorization': 'Bearer {0}'.format(ACCESS_TOKEN), 'Content-Type': 'application/x-www-form-urlencoded' } ) return res #This function to check MFA enabled when user before login def enrolled(request): email = request.POST['email'] res = requests.post( 'http://0.0.0.0:8000/api/users/email/', data={ 'account_name': email, }, headers={ 'Authorization': 'Bearer {0}'.format(ACCESS_TOKEN), 'Content-Type': 'application/x-www-form-urlencoded' } ) ''' the error am getting is due to username and password being of type byte instead of string ,so if there is the way of converting them into string ''' Quit the server with CONTROL-C. b'jdv' … -
Django - Serializer throwing "Invalid pk - object does not exist" when setting ManyToMany attribute where foreign keyed object does exist
So below I have some code that tests the functionality where someone creates a post and that post has a hash_tag which is "#video" in this case. The code takes the Post body and uses regex to find any word that starts with "#". If it does then it creates or gets that HashTag from the HashTag table. Then sets that list of HashTag to the hash_tags attribute under Post. For some reason the CreatePostSerializer serializer is throwing an exception that doesn't make sense. The serializer is throwing the exception ValidationError({'hash_tags': [ErrorDetail(string='Invalid pk "[\'video\']" - object does not exist.', code='does_not_exist')]}). The reason this doesn't make sense is because when I debug and set a breakpoint right after except Exception as e under views.py this is what I get >>>e ValidationError({'hash_tags': [ErrorDetail(string='Invalid pk "[\'video\']" - object does not exist.', code='does_not_exist')]}) >>>HashTag.objects.get(pk='video') <HashTag: HashTag object (video)> >>>request.data['hash_tags'] ['video'] So the >>> represents what I input into the debugger. I'm essentially stopped at the line return Response... and we can see e is the ValidationError I mentioned, but we can see that the object it claims doesn't exist does indeed exist. Why is the serializer throwing a "ValidationError - object does not exist" … -
Django Inner join Parent model with child model
I have this tables class OtherTable(models.Model): #some attributes class Parent(models.Model): #some attributes class Child1(models.Model): group = models.ForeignKey(Parent) #more attributes class Child2(models.Model): group = models.ForeignKey(Parent) #more attributes class Child3(models.Model): group = models.ForeignKey(Parent) other_table = models.ForeignKey(OtherTable) #more attributes how can join all tables? I want to perform the equivalent SQL query using django's ORM: select * from parent inner join child1 on parent.id = child1.parent_id inner join child2 on parent.id = child2.parent_id inner join child3 on parent.id = child3.parent_id inner join othertable on other.id = child3.other_table_id -
How to filter query by multiple values using DRF, djagno-filters and HyperlinkedIdentityField values
Main target is to get query set based on multiple values in query. Business logic is to get all contracts for multiple drivers. Example: request url: /api/contract/?driver=http://localhost:8000/api/driver/1,http://localhost:8000/api/driver/2 Response should be all contracts for these two drivers. Driver Serializer: class DriverSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='driver-detail', read_only=True ) class Meta: model = Driver fields = [ 'url', 'id', 'first_name', 'last_name', ] Contract serializer: class ContractSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='contract-detail', read_only=True ) driver = serializers.StringRelatedField(many=False) class Meta: model = Contract fields = [ 'url', 'id', 'contract_detail_fields', 'driver', ] Contract View class ContractViewSet(viewsets.ModelViewSet): serializer_class = serializers.ContractSerializer queryset = Contract.objects.all() permission_classes = (IsAuthenticated,) filter_backends = [DjangoFilterBackend] filterset_class = ContractFilter ContractFilter: class ContractFilter(FilterSet): driver = CustomHyperlinkedIdentityFilterList('driver') What I have tried is to make custom filterField based on answer by Sherpa class CustomHyperlinkedIdentityFilterList(django_filters.BaseCSVFilter, django_filters.CharFilter): def filter(self, qs, value): values = value or [] for value in values: qs = super(CustomHyperlinkedIdentityFilterList, self).filter(qs, value) return qs Answer is ValueError: Field 'id' expected a number but got 'http://localhost:8000/api/drivers/driver/3/'. Then I am trying to modify to filter by id not urlField and changing this line qs = super(CustomHyperlinkedIdentityFilterList, self).filter(qs, value) to this: qs = super(CustomHyperlinkedIdentityFilterList, self).filter(qs, get_id_from_url(value)) where get_id_from_url is: def get_id_from_url(url): return int(resolve(urlparse(unquote(url)).path).kwargs.get('pk')) But it return me only contracts for … -
Speed up order_by and pagination in Django
Currently I have this result: That's not bad (I guess), but I'm wondering if I can speed things up a little bit. I've looked at penultimate query and don't really know how to speed it up, I guess I should get rid off join, but don't know how: I'm already using prefetch_related in my viewset, my viewset is: class GameViewSet(viewsets.ModelViewSet): queryset = Game.objects.prefetch_related( "timestamp", "fighters", "score", "coefs", "rounds", "rounds_view", "rounds_view_f", "finishes", "rounds_time", "round_time", "time_coef", "totals", ).all() serializer_class = GameSerializer permission_classes = [AllowAny] pagination_class = StandardResultsSetPagination @silk_profile(name="Get Games") def list(self, request): qs = self.get_queryset().order_by("-timestamp__ts") page = self.paginate_queryset(qs) if page is not None: serializer = GameSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(qs, many=True) return Response(serializer.data) Join is happening because I'm ordering on a related field? My models looks like: class Game(models.Model): id = models.AutoField(primary_key=True) ... class Timestamp(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, related_name="timestamp", on_delete=models.CASCADE) ts = models.DateTimeField(db_index=True) time_of_day = models.TimeField() And my serializers: class TimestampSerializer(serializers.Serializer): ts = serializers.DateTimeField(read_only=True) time_of_day = serializers.TimeField(read_only=True) class GameSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) timestamp = TimestampSerializer(many=True) fighters = FighterSerializer(many=True) score = ScoreSerializer(many=True) coefs = CoefsSerializer(many=True) rounds = RoundsSerializer(many=True) rounds_view = RoundsViewSerializer(many=True) rounds_view_f = RoundsViewFinishSerializer(many=True) finishes = FinishesSerializer(many=True) rounds_time = RoundTimesSerializer(many=True) round_time = RoundTimeSerializer(many=True) time_coef = TimeCoefsSerializer(many=True) totals = … -
Trouble displaying inline forms of a ModelAdmin
I am encountering what seems to me a weird bug when rendering Inline forms on the "Add" view of a ModelAdmin. Here is a minimum example with Django version 2.2.4. in models.py: class MyModel(models.Model): text = models.CharField(max_length=100) class RelatedModel(models.Model): parent = models.ForeignKey(MyModel, null=False, on_delete=models.CASCADE) number = models.DecimalField(decimal_places=2, max_digits=10, null=False, blank=False) in admin.py: class RelatedModelInlineTabular(admin.TabularInline): model = RelatedModel show_change_link = False fields = ("number", ) class TestMyModelCreate(admin.ModelAdmin): fields = ['text', ] inlines = [RelatedModelInlineTabular] admin.site.register(MyModel, TestMyModelCreate) Steps to replicate Login to django admin website open the "add" view for MyModel (i.e. navigate to the list of Models and click on the "Add new" button) Expected result The form displays an empty text field. Below that, an Inline form is displayed with 3 empty rows for potential related instances of RelatedModel Actual result The Inline form is displayed twice, each instance with its own 3 empty rows, as if I had specified it twice. I attach a screenshot below of the actual page (Discount is the name of the related Model). I tried and I get the same result with both StackedInline and TabularInline. Am I making some trivial error here that could explain what's happening? Or is this is a known … -
404 Error on TextArea in Admin interface, Django Summernote
For texteditor i use Summernote Django, but i got error 404 on admin interface. summernote editor id doesn't find. that's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('summernote/', include('django_summernote.urls')), ] -
How to get updated class variable value in Django
Hello~ I'm having trouble getting the updated value of the class variable. When ConnectTestAPI is called after "p_request" function executed, the class variables which are "result" and "orderNo" should updated in the "post" function. Then I want to receive the updated value of class variables by looping while statement in "p_request" function. However, despite setting the values of class variables with the post request, when the while statement is run, the corresponding values are still empty and 0 value respectively, so the while statement cannot be terminated and result in a time out error. Here is my source code. Thank you in advance!!!! class ConnectTestAPI(APIView): result="" orderNo=0 def post(self, request): data = request.data ConnectTestAPI.result = data['result'] ConnectTestAPI.orderNo = data['orderNo'] print(ConnectTestAPI.result) # I could successfully get data from POST request here! print(ConnectTestAPI.orderNo) # I could successfully get data from POST request here! return HttpResponse("ok") def p_request(): data = { "a" : 1234, "b" : 5678 } data = json.dumps(data,ensure_ascii=False).encode('utf-8') con = redis.StrictRedis(outside_server['ip'],outside_server['port']) con.set("data_dict", data) while True: if ConnectTestAPI.result != "" and ConnectTestAPI.orderNo != 0: break res_result = ConnectTestAPI.result res_orderNo = ConnectTestAPI.orderNo return res_result, res_orderNo -
Url pattern in django rest framework
I am trying to use modelviewset and for that I have to use router in urls file for routing. Everything seems to be working as expected but my urls are highlighted as if the code is just ignored in my pycharm. It is as follows: Here as we can see above, it is highlighted by pycharm as if the code doesnt have any part in the project or is being ignored. When I use apiview and do not use the routers, the urls are not highlighted and are shown normally. What is the issue?? -
How to turn on and off pagination in django rest?
I tried like this but it is returning paginated queryset even if I call api with my/api/?no-page I want to disable pagination and show all data if no-page in query params else paginate queryset as usual. class CustomPagination(PageNumberPagination): def paginate_queryset(self, queryset, request, view=None): if "no_page" in request.query_params: return None return super().paginate_queryset(queryset, request, view) -
How to update a nested object in Django?
I'm trying to update a nested object in Django but facing an error with sub-object id's already existing. I have these two Models: class Plan(models.Model): planId = models.CharField(primary_key=True, max_length=100, unique=True) name = models.CharField(max_length=200) class PlanEvent(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) id = models.CharField(primary_key=True, max_length=100, unique=True, blank=False, null=False) done = models.BooleanField() title = models.CharField(max_length=100, blank=True) I have an update method in my PlanSerializer and it works if I send a PUT request with an empty events-list, but if I include some events I want to update, I get an error: { "events": [ { "id": [ "plan event with this id already exists." ] } ] } This is my PlanSerializer update method: class PlanSerializer(serializers.ModelSerializer): events = PlanEventSerializer(many=True) class Meta: model = Plan fields = ('planId', 'name', 'events') def update(self, instance, validated_data): events_validated_data = validated_data.pop('events') events = (instance.events.all()) events = list(events) instance.name = validated_data.get('name', instance.name) instance.save() for event_data in events_validated_data: event = events.pop(0) event.done= event_data.get('done', event.done) event.title = event_data.get('title', event.title) event.save() return instance So I'm not getting to the update-method at all when I pass events to the PUT -payload, what I'm doing wrong? -
How to display Model Object Count In Django Admin Index
I am trying to display the count of objects of each model. For this i have edited env > lib > django > contrib > templates > admin > app_list.html, bellow is the code. I am having to doubts here. I know this is not optimal solution where editing directly in env django folder. So how i can edit the app_list.html so that i can display the count. I tried {{model}}, but was not able to display count, always come as blank as you can see in image. Possible out i tried in template html- {{model}} Object - {'name': 'Exam categorys', 'object_name': 'ExamCategory', 'perms': {'add': True, 'change': True, 'delete': True, 'view': True}, 'admin_url': '/admin/quiz/examcategory/', 'add_url': '/admin/quiz/examcategory/add/', 'view_only': False} {{model.count}} Object - {{model.all}} Object - {{model.objects.all}} Object - ---------------------------------------------------------------- env > lib > django > contrib > templates > admin > app_list.html ---------------------------------------------------------------- {% load i18n %} {% if app_list %} {% for app in app_list %} <div class="app-{{ app.app_label }} module{% if app.app_url in request.path %} current-app{% endif %}"> <table> <caption> <a href="{{ app.app_url }}" class="section" title="{% blocktranslate with name=app.name %}Models in the {{ name }} application{% endblocktranslate %}">{{ app.name }}</a> </caption> {% for model in app.models %} <tr class="model-{{ … -
mod_wsgi-express module-config command not working during django deployment on apache
During the deployment of my Django Project with Apache and mod_wsgi on Windows10. I have installed Apache24 in my C drive and its working fine. After that I have installed openpyxl and mod_wsgi with the commands "pip install openpyxl" and "pip install mod_wsgi" respectively. Both has been installed successfully. But when I try to run this command "mod_wsgi-express module-config" on the command prompt it shows me error "mod_wsgi-express : The term 'mod_wsgi-express' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." error picture -
unable to predict in my web model after conversion of keras_savedmodel
After tensorflowjs conversion i got my model.json and weights.bin files like tutorials suggested i posted it in my github repository and used it to load my web app but the predictions are horrible and i dont know how to include labels to identify while predicting the models[ const video = document.getElementById('webcam'); const liveView = document.getElementById('liveView'); const demosSection = document.getElementById('demos'); const enableWebcamButton = document.getElementById('webcamButton'); const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0) var vidWidth = 0; var vidHeight = 0; var xStart = 0; var yStart = 0; // Check if webcam access is supported. function getUserMediaSupported() { return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia); } // If webcam supported, add event listener to activation button: if (getUserMediaSupported()) { enableWebcamButton.addEventListener('click', enableCam); } else { console.warn('getUserMedia() is not supported by your browser'); } // Enable the live webcam view and start classification. function enableCam(event) { // Only continue if the model has finished loading. if (!model) { return; } // Hide the button once clicked. enableWebcamButton.classList.add('removed'); // getUsermedia parameters to force video but not audio. const constraints = { video: true }; // Stream video from browser(for safari also) navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" }, … -
psycopg2 undefined column on column value
psycopg2 is being a preteen child to me right now. cur = conn.cursor() url = "https://shofi-mod.s3.us-east-2.amazonaws.com/" + str(rawbucketkey) query = f"""UPDATE contentcreatorcontentfeedposts_contentfeedpost SET picturemediatype = TRUE, mediakey ={rawbucketkey}, mediaurl= "{url}", active = TRUE, postsubmit = FALSE WHERE contentcreator_id ={userid} AND id ={contentpostid}; COMMIT;""" cur.execute(query) cur.close() But I keep getting an error: [ERROR] UndefinedColumn: column "https://shofi-mod.s3.us-east-2.amazonaws.com/061909729140543151" does not exist LINE 3: mediaurl= "https://shofi-mod.s3.us-east-... ^ Traceback (most recent call last): File "/var/task/lambdarunner.py", line 163, in lambda_handler cur.execute(query) and my database does in fact have a media column class ContentFeedPost(models.Model): contentcreator = models.ForeignKey(ContentCreatorUsers, on_delete=models.CASCADE) creationtimestamp = models.DateTimeField(auto_now_add=True) likes = models.BigIntegerField(default= 0) favoritedtimes = models.BigIntegerField(default=0) tipcount = models.IntegerField(default=0) mediakey = models.CharField(max_length=200, null=True, blank=True) mediaurl = models.CharField(max_length=200, null=True, blank=True) audiomediatype = models.BooleanField(default=False) videomediatype = models.BooleanField(default=False) audiotitle = models.CharField(max_length=100, null=True, blank=True) videoplaceholderimage = models.CharField(max_length=200, blank=True, null=True) videoplaceholderimagekey = models.CharField(max_length=200, blank=True, null=True) audioplaceholderimage = models.CharField(max_length=200, blank=True, null=True) audioplaceholderimagekey = models.CharField(max_length=200, blank=True, null=True) picturemediatype = models.BooleanField(default=False) postsubmit = models.BooleanField(default=True) posttext = models.CharField(max_length=1000, blank=True, null=True) active = models.BooleanField(default=False) Above is a django ORM definition whats weird is that it looks like its complaining about the value im trying to set the column mediaurl to. This makes no sense. Is there something Im doing wrong that is obvious? -
Is there a requirement needed to enable Ubuntu to allow allowed_hosts in django
I hope all of you are fine I have one problem. I can only access localhost through my browser whenever I try to add anything else in the allowed_host. The browser cannot even detect it. I am new on Linux so I wanted to know where I was going wrong maybe I have to install a package or something? -
How to save a django model with multiple images?
I've been betting for an hour, but apparently I don't understand something. There is a task to write a scraper with the django admin panel and everything is fine and works here. Now i need to save all the data to the database and here is the problem, only one photo appears in the django admin panel, but everything is downloaded in the media folder. # models.py from django.db import models class Apartment(models.Model): rooms = models.CharField('кол-во комнат', max_length=64) price = models.CharField('цена', max_length=10) address = models.CharField('Адрес', max_length=256) desc = models.TextField('описание') floor = models.CharField('этаж', max_length=5) def __str__(self): return self.address class Meta: verbose_name = 'квартира' verbose_name_plural = 'квартиры' class Image(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE) img = models.ImageField(upload_to='media/') class Meta: verbose_name = 'фото' verbose_name_plural = 'фото' class Url(models.Model): created = models.DateTimeField(auto_now_add=True) url = models.URLField('ссылка') def __str__(self): return self.url class Meta: verbose_name = 'ссылка' verbose_name_plural = 'ссылки' ordering = ['-created'] #save function def save_data(apartments_list): for ap in apartments_list: im = Image() try: apartment = Apartment.objects.create( rooms=ap['rooms'], price=ap['price'], address=ap['address'], desc=ap['desc'], floor=ap['floor'], ) for image in ap['photos']: pic = urllib.request.urlretrieve(image, image.split('/')[-1])[0] im.img = im.img.save(pic, File(open(pic, 'rb'))) im.apartment = apartment except Exception as e: print(e) break -
how i store user input data in a file that give from front side of the browser?
Actually i want to store data in file that give from front side of the browser. well we can use form or ModelForm or maybe we give input in json and that json data store in a file..anyone have an idea or any hint? -
How to make a query from a selected choice from the user from a drop-down list in Django
I am new here. In an internship context, I have to developp a website in which the user will have the opportunity to select a program, a localisation or a thematic he wants to visualise in a heatmap. To do so, I decided to use Django. I am encoutering 2 issues : First one : I have a mysql database constituted with 1 table with the location names (detailed in many columns) and the coordinates, and one table by program of the raw datas. I need to find a way to join the two tables but one localisation name can have different coordinates depending on the program. So i need to concatenate 2 columns by table (2 columns from the raw datas that I join to two columns from the table with the coordinates) For now I have thought about using new_var = table.objects.annotate but i cannot join the two newly variables ... Do you have any ideas ? Secondly : The user is supposed to choose a localisation from a drop-down list, that i can use to filter my database and display the map as he wishes. For now I have that : (views.py) ''' def map(request): m = … -
Postgres createdb and create database is not working in Ubuntu 18.04
I have a Django project I am trying to set up on Ubuntu and am creating a new database in PostgreSQL 14. The default root user is Postgres as usual. Then I tried creating a new user with my Linux username "abc" with all the privileges: "SUPERUSER", "CREATEDB", etc. Everything worked fine and a new user was created. And it was suggested that I create a database with the same name "abc". So, I did CREATE DATABASE abc; in the psql shell, it gives no error and results in nothing. I tried createdb abc or creatdb in the bash terminal but this also does nothing either. The solution from this SO answer link does not work for me at all. I also tried this which did not do anything. I ultimately just want to be able to create the database for my Django project, which I am not able to do, and I have now no clue what I am doing wrong. Here's the command I am using to set up the Django project db: # create new user who will be the db owner # on Ubuntu, root user is postgres createuser -P <new_user_name> -U <root_user> # if you're … -
how to invite people from social to your django app [closed]
I am creating an app where I want some buttons just like you see on most of the apps where people can invite other people on app. like facebook, twitter or any other social link. if you click on it you can share the link on whatsapp or all of these sites and when the person who I sent click on that link he should redirect to my site