Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
comment not being submitted by my django form
I want my users to be able to add comments under a transfernews [I am creating a sports related website], I tried this code, but for some reason, it is not working, I can add comments manually from the admin page but can't from the comment form. Can anyone please tell me how to fix my code? My models.py: class Transfernews(models.Model): player_name = models.CharField(max_length=255) player_image = models.CharField(max_length=2083) player_description = models.CharField(max_length=3000) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.transfernews.player_name, self.user.username) My forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) My views.py: def transfer_targets(request): transfernews = Transfernews.objects.all() form = CommentForm(request.POST or None) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = request.user new_comment.transfernews_id = transfernews.id new_comment.save() return redirect(request.path_info) return render(request, 'transfernews.html', {'transfernews': transfernews, 'form': form}) My html file: {% for transfer in transfernews %} <h2>Comments...</h2> {% if not transfer.comments.all %} No comments Yet... {% else %} {% for comment in transfer.comments.all %} <strong> {{ comment.user.username }} - {{ comment.date_added }} </strong> <br/> {{ comment.body }} <br/><br/> {% endfor %} {% endif %} <hr> <div>Comment and let us know your thoughts</div> <form … -
Populating parent model from child model form in django
I have a web interface in which I can add entries to a child model, which I created in Django. I can populate the child model by using dropdown menus which will display the items currently stored in the parent models. I would like to be able to actually insert a new item in the parent model from within the same form. I have the following model, which works fine if I want to populate the child model (results class) using already existing parent model (project table and objects_table) entries. models.py class project_table(models.Model): project = models.CharField(max_length = 100, unique = True) def __str__(self): return u'{0}'.format(self.project) class objects_table(models.Model): object = models.CharField(max_length = 50) def __str__(self): return u'{0}'.format(self.object) class results_table(models.Model): object_id = models.ForeignKey(objects_table, on_delete = models.PROTECT) project_id = models.ForeignKey(project_table, on_delete = models.PROTECT) date = models.DateTimeField(default = timezone.now) path = models.CharField(max_length = 500) def get_absolute_url(self): return reverse('result-detail', kwargs = {'pk': self.pk}) My view is: views.py class ResultCreateView(LoginRequiredMixin, CreateView): model = results_table fields = ['object_id','project_id', 'date', 'path'] def form_valid(self, form): form.instance.operator = self.request.user return super().form_valid(form) and the HTML: {% extends "queryd/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Result</legend> {{ form|crispy … -
Only get Cors Header error when accessing media files, rest of the app works fine (DRF, pythonanywhere, React)
This is happening on both chrome and firefox. I have a react app that communicates fine with my django rest framework backend until I try to access an uploaded mp3 media file. I then get: " has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." If I click on the error media link within chrome console it will take me to the uploaded mp3 and it will play fine. My app is deployed on Pythonanywhere. My settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tagging', 'rest_framework', 'corsheaders', 'rest_framework.authtoken', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'STATIC') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'MEDIA') CORS_ALLOW_ALL_ORIGINS = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } urls: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('tagging.urls')), path('api/api-token-auth/', views.obtain_auth_token) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have static & media files setup within the pythonanywhere web app: URL:/STATIC/ Directory: /home/username/project/STATIC URL:/MEDIA/ Directory: /home/username/project/MEDIA not sure why this is occurring, any help would be much appreciated. -
can set string data to state with axios in reactjs
I want to save the string received from API in the state, but it can't. First I wrote a Python code as follows that returns the first 3 letters of the username (each username is entered so that the first three letters specify its type). this is Django(python) code: from django.shortcuts import redirect, render from rest_framework.views import APIView from rest_framework.response import Respons class usertype(APIView): def get(self,request,format=None): try: user=request.user except: raise ValueError('error') return Response({ 'username':user.username[:3], }) then i write this code in react for separate dashboards: import React, { Component } from 'react' import { render } from 'react-dom'; import DashboardS from './Students/DashboardS'; import DashboardT from './Teachers/DashboardT'; import axios from 'axios'; const api=axios.create({ baseURL:'http://127.0.0.1:8000/accounts/usertype/' }) export default class App extends Component { constructor(props){ super(props); this.state={ usertype:'', showS:false, showT:false, } this.showDash=this.showDash.bind(this); this.getusertype=this.getusertype.bind(this); } componentDidMount(){ this.getusertype(); this.showDash(); } getusertype(){ api.get('/').then(res=>{ this.setState({ usertype:res.data.username, }); console.log(res.data.username); // out is std for stduent user }); } showDash(){ switch(this.state.usertype){ case "std": this.setState({ showS:true,showT:false, }) break; case "tcr": this.setState({ showS:false,showT:true, }) break; } } render() { return ( <div> {this.state.showD && <DashboardS/>} {this.state.showP && <DashboardT/>} </div> ) } } how can i solve this problem. help me. -
Gunicorn process never die
I have a nginx + gunicorn django application, those process never dies for some reason until no-response: Once it run on local windows 10 env - It works really good no memory leak hangs. I think local only "fork" (win dont fork IO know) one main, but Y gunicorn process never die ? -
How to resolve 'Import "django.contrib" could not be resolved from sourcePylancereportMissingModuleSource'?
This error suddenly came up when I created a new django project. I used pip to install all the packages in the virtual environment.enter image description here -
'Contact.Contact' has no ForeignKey to 'Order.Order' error using django extra views
I'm trying to use django extra views to create an Order with a Contact inline formset but i'm getting the following error : 'Contact.Contact' has no ForeignKey to 'Order.Order'. models.py class Contact(models.Model): ... class Order(models.Model): contact = models.OneToOneField(Contact, on_delete=models.CASCADE, default="") views.py class ContactInline(InlineFormSetFactory): model = Contact fields = ['name', 'email'] class CreateOrderView(CreateWithInlinesView): model = Order inlines = [ContactInline] fields = ['customer', 'name'] template_name = 'order_and_items.html' I am wordering if the problem is due to the OneToOne relationship between Contact and Order. -
Filter on custom field across multiple models that import from Wagtail core Page
I have two custom Page models that share a field in common, for example: class CustomPageModelOne(Page): custom_field = models.IntegerField() ... class CustomPageModelTwo(Page): custom_field = models.IntegerField() ... I need to run, ideally, a single filter across the two types of custom Page models. The Wagtail docs say I can use an exact_type method to specify multiple models inheriting from core Page, so I am trying some variations of the following: Page.objects.exact_type(CustomPageModelOne, CustomPageModelTwo).filter(custom_field=123) However, when I try to filter any QuerySet that uses both models, I get an error: django.core.exceptions.FieldError: Cannot resolve keyword 'custom_field' into field. How can I query across multiple Wagtail custom Page models that share a field in common? Note: I have considered creating an abstract class inheriting from Page, but cannot import that abstract model in the file where it is needed. Abstract class example: class CustomFieldModel(Page): custom_field = models.IntegerField() class Meta: abstract = True class CustomPageModelOne(CustomFieldModel): pass class CustomPageModelTwo(CustomFieldModel): pass -
python filter returns none if any one input is not present in combination django
i am creating a model in for a literature in which we can type english,german,french etc.. , my model may be containing english,german,french. if i put these 3 values in it , it shows me correct output but if type english,german it returns none because one condition failed, but in fact i want it in such a way that it return that perticular object if that condition met, if i write english,german,french and model contains only english,german it should return english,german instead of none def resolve_codepool_advanced_lang5(root,info,lang1,lang2,lang3,lang4,lang5): return Codepool_Advanced.objects.filter(codepool_advanced_language1=lang1,codepool_advanced_language2=lang2,codepool_advanced_language3=lang3,codepool_advanced_language4=lang4,codepool_advanced_language5=lang5) -
Uncaught TypeError: Cannot read property 'fields' of undefined at Object.success
I wanted to use ajax for showing all comments that are responding to a song. The song model contain a many to many field for the comments model. Im having trouble with the serializer for django or im having trouble with receiving the data from my view. Im not quite sure which it is. View.py: def commentview(request): if request.is_ajax and request.method =="GET": song_id = request.GET.get("song_id",None) song = get_object_or_404(Song,pk=song_id) comments = song.comments.all() ser_comments = serializers.serialize('json', comments) return JsonResponse({"instance": ser_comments}, status=200) playlist.html: {% block javascript %} <script> function comments( id) { $.ajax({ type: 'GET', url: "{% url 'app:commentview' %}", data: { "song_id": id }, success: function (response) { var comments = JSON.parse(response["instance"]); for (var i = 0; i <= comments.length; i++) { var field = comments[i]["fields"]; $("popup" + id).prepend( '< h5 > ${ field["member"]|| "" }</h5 >' + '< p > ${ field["text"]|| "" }</p >' + '<br>', ) } $("popup" + id).prepend( '<textfield id="comment' + id + '"></textfield>' + '<button onclick="postComment(' + id + ')">Comment</button>', ) }, error: function (response) { } }) } </script> {% endblock javascript %} the error code i get: 1:520 Uncaught TypeError: Cannot read property 'fields' of undefined at Object.success (1:520) at i (jquery-3.2.1.min.js:2) at Object.fireWith … -
django admin css broken - vertical scroll runs over all parts of page
I am running django 3.1.4 and my admin css broke somehow: when scrolling, the list of the products is appearing "behind" other menu points. so instead of just the products being scrolled below the last point of the admin, all of them scroll. which css setting might be the key here (the admin css is too long to post here I guess, but I am happy to share what helps). -
Why is Django retrieving all the reverse foreign objects
I have the following models created in django: class A(models.Model): route = models.ForeignKey('B', related_name='b') class B(models.Model): name = models.CharField(max_length=100) And I want to filter the elements of 'B' without accessing the elements of A. The problem is that when I run the following query (supposing there are 4 objects of A related to one object of B with id equal to 1): B.objects.filter(id='1') I get printed 4 different sql queries, fetching all related objects of A. I do not know why that's happening. I have tried B.objects.filter(id='1').select_related('b') But it does not work for some reason. I do not want to do those hits to the database, ideally, I would want to ignore/exclude those objects because I only want the objects of B. Additional info: django version: 1.11 python version: 2.7 -
Why am i getting a ModuleNotFoundError when i add rest_framework to my django app
I created a new django app and installed djangorestframework using pipenv version 2020.11.15 and regestered it in the settings.py file # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leads', 'rest_framework' ] i got this error on running python manage.py makemigrations C:\Users\eliHeist\Python Workspace\lead_manager_react_django\leadmanager>python manage.py makemigrations 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 "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' What is going on? -
How to add searchable choice field in django form
I am looking for implementing searchable choice field (searchable dropdown) in django using django forms and models. This choice field will be populated from database. -
Single page application using django-Nav Bar for django app
In Angular,we can use routing to create SPAs . So I can have a navigation bar that's common for all templates(or written only once). Basically only required part of the page loads everytime . But in django,so far I haven't seen anything like it. Do i have to include the code for the Nav bar in each template file? -
DRF IntegrityError: null value in column "quiz_inst_id" violates not-null constraint
models.py class Quiz(models.Model): admin = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) title = models.CharField(max_length=255) def __str__(self): return self.title class Question(models.Model): quiz_inst = models.ForeignKey("Quiz", related_name="questions", on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.body serializers.py class QuizSerializer(serializers.ModelSerializer): questions = serializers.PrimaryKeyRelatedField( many=True, queryset=Question.objects.all(), ) class Meta: model = Quiz fields = ('id', 'admin', 'title', 'questions') read_only_fields = ('id', 'admin') class QuestionSerializer(serializers.ModelSerializer): quiz_title = serializers.ReadOnlyField(source='quiz_inst.title') class Meta: model = Question fields = ('id', 'quiz_title', 'body') read_only_fields = ('id', 'quiz_title') views.py class QuizViewSet(viewsets.ModelViewSet): queryset = Quiz.objects.all() serializer_class = QuizSerializer def perform_create(self, serializer): serializer.save(admin=self.request.user) class QuestionViewSet(viewsets.ModelViewSet): queryset = Question.objects.all() serializer_class = QuestionSerializer error app_1 | django.db.utils.IntegrityError: null value in column "quiz_inst_id" violates not-null constraint app_1 | DETAIL: Failing row contains (2, wefwerfwe ewfw ef, 1, null, null). Why does foreignkey not getting assigned? Would be appreciated if someone could explain or link me a documentation to read. I've read some other similar questions but i still can't figure out what shoud i do. -
How to compress the new uploaded images using PIL before saving to AWS S3 Bucket?
PIL has really good image processing abilities, It allows me to shrink the size by over 90% and the quality still remains, But in order to shrink an image you have to convert it to jpeg, But AWS is saying set it to "png" or we will ignore your "jpeg" code Any idea why is Amazon like this? And is there a way to shrink Image on the Django backend with AWS without using services such as AWS Lambda? The code is provided below: from django import forms from .models import Card from django.core.files.storage import default_storage as storage from PIL import Image class CardForm(forms.ModelForm): class Meta: model = CARD fields = ('photo1',......) def save(self, *args, **kwargs): card = super(cardForm, self).save() image = Image.open(card.photo1) storage_path = storage.open(card.photo1.name, "wb") image.save(storage_path, "jpeg", quality=10, optimize=True) # set to png or aws ignores the code storage_path.close() return card -
I can't migrate on heroku. Using Django MySQL
I can't migrate on Heroku. Using Django and MySQL. I don't what wrong with it. There are some wrongs on setting_mysql.py? I got an error like this. (base) mypc@mypc website % heroku run python manage.py migrate Running python manage.py migrate on ⬢ myapp... up, run.3308 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/MySQLdb/__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/MySQLdb/connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") -
Auto calculate and return a field based on request in Django rest framework
I have a list of books with pincode of the location it was added from. I am getting a post request with pincode of user who wants to get such list. The list needs to be sorted according to the distance from the user. Although I have a function to calculate the distance, I want to return a dynamic field named 'distance' in response. My Book models is like:- class Book(TimestampedModel): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True ) name = models.CharField(max_length=20, blank=True) desc = models.CharField(max_length=140, blank=True) is_active = models.BooleanField(default=True, blank=False) price = models.IntegerField(null=True) pincode = models.IntegerField(null=False) My serializer is like:- class BookSerializer(serializers.ModelSerializer): """Serializer for book object""" class Meta: model = Book fields = ('id', 'user', 'name', 'desc', 'is_active', 'sold_to', 'is_sold', 'age', 'price', 'created_at', 'updated_at', 'pincode') and my view looks like:- class BookViewSet(viewsets.ModelViewSet): serializer_class = serializers.BookSerializer queryset = Book.objects.all() query_params = self.request.query_params def get_queryset(self): queryset = Book.objects.all() if('pincode' in query_params): pincode = query_params['pincode'] try: for counter, instance in enumerate(queryset): **instance.distance = dist.query_postal_code( pincode, instance.pincode)** queryset = sorted(queryset, key=**attrgetter('distance')**) except Exception as ex: print(ex) return queryset As you can see, I am able to calculate the distance in the view, I am not sure how to send this in response. Please help … -
Can beginners really help to any python or django open source project?
I've been studying Flask, Django, and Selenium Webdriver for more than 6 moths. I'am actually developing personal projects but i was wondering if with my limited knowledge I could really help an open-source project too. Check my Github account if you want -
How to pronounce django machina?
I was working with my team on a Django project. But in a regular stand-up meeting, I don't know how to pronounce "Machina". -
How can I get the value of the last column taking the first column as a reference?
I want to get the value depending on the code that is, if it is the number 10 that I get the value of TYPE Query: This query return the parameter cod this table is on mysqlserver sentencia ="exec [PR].[dbo].[PT_GET_PR]" + "'" + m + "','" + str(rec) + "','" + orden + "'" + ",'" + str(fecha_i) + "'," + "'" + str(fecha_f) + "'" Model: this table is on postgre and i want to get the value cod same of the last query and take the value type on my table on postgre class items(models.Model): COD_= models.CharField('COD', max_length=200) Descripcion= models.CharField('Descripcion', max_length=200) TAB= models.CharField('TAB_Sistrade', max_length=200) TIPO= models.CharField('TIPO', max_length=200) -
Try except in django admin panel
I have a function in my models.py that adds the news I pass to it via a URL using OpenGraph. This process works fine, but there are some websites that give me an error, how can I use a try except to control this error and the application does not crash? When the error occurs, I would like the application in the admin panel to return me to the same place where it was before, but indicating the error. Best regards and thank you very much! My models.py: class Post(models.Model): title = models.CharField(max_length=200, verbose_name="Título", null=True, blank=True) content = RichTextField(verbose_name="Contenido", null=True, blank=True) published = models.DateTimeField(verbose_name="Fecha de publicación", default=now, null=True, blank=True) image = models.ImageField(verbose_name="Imagen", upload_to="blog", null=True, blank=True) author = models.ForeignKey(UserManegement, verbose_name="Autor", on_delete=models.CASCADE) categories = models.ManyToManyField(Category, verbose_name="Categorias", related_name="get_posts") url_web = models.URLField(verbose_name="URL", null=True, blank=True) created = models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creacion') updated = models.DateTimeField(auto_now=True, verbose_name='Fecha de ediccion') class Meta: verbose_name = "entrada" verbose_name_plural = "entradas" ordering = ['-created'] def __str__(self): return self.title The function in which I want to insert the try except. It is in the same models.py: @receiver(pre_save, sender=Post) def url_processor(sender, instance, *args, **kwargs): if instance.url_web: title, description, image = web_preview(instance.url_web) instance.title = title instance.content = description path = 'blog/' + uuid.uuid4().hex + … -
How do i append an array of objects inside an array of objects
@require_http_methods(["GET"]) @login_required def get_questions(request): res = {} questions = models.Questions.objects.raw( """ SELECT SELECT Q.question_id,Q.question,Q.description,Q.qn_total_mark,QP.part_desc, QP.part_total_marks, PMA.part_model_ans,PMA.part_answer_mark,PMA.part_answer_id FROM "QUESTIONS" Q LEFT JOIN "QUESTIONS_PART" QP ON QP.question_id = Q.question_id LEFT join "PART_MODEL_ANSWER" PMA ON PMA.part_id = QP.part_id """ ) for question in questions: if question.question_id not in res: res[question.question_id] = { "key": question.question_id, "question": question.question, "description": question.description, "qn_total_mark": question.qn_total_mark, "question_parts": [ { "part_desc": question.part_desc, "part_model_ans": question.part_model_ans, "part_guided_answer":[ { "part_answer_id":question.part_answer_id, "part_model_ans": question.part_model_ans, "part_answer_mark": question.part_answer_mark, } ], "part_total_marks": question.part_total_marks, } ] } else: res[question.question_id]["question_parts"].append( { "part_desc": question.part_desc, "part_model_ans": question.part_model_ans, #part guided answer is appended in here i think "part_total_marks": question.part_total_marks, } ) return success({"res": list(res.values())}) What am i trying to do is to append the array inside the array of objects for use but i do not think this is a good idea, is it possible to do it like this and if so how could it be done? Also is there a better alternative for it -
Angular web application codebase for mobile apps?
I want to build a website the following way: Backend: Django REST Framework Frontend: Angular I do not want to discard the idea to build mobile apps for Android and IOS in the future as well. I found out that Ionic is a possibility to use an Angular codebase easily for Android and IOS mobile apps. Now my questions: Is that correct and are there alternatives? Can I build my web application with Angular without thinking in mobile apps or do I have to write specific Angular code from the beginning such that I can use the codebase for Android and IOS mobile apps later? Thank you!