Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: post form and post list on the same page
I make a site with multiple users, making posts with images and ability to add/remove friends. So it's easy to make two different pages for post list and creating a new one. But of course it looks better when you can read posts and make new at the same place. As I understand (learn django for less than a month), I can't connect 2 views to the same url, so the most logical way I see is to join 2 views in one, I also tried to play with template inheriting to render post form by including template, but actually it doesn't work. Below you can see my views, Post model, and templates. Thank you for attention. views.py: from braces.views import SelectRelatedMixin from . import models from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ('user',) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ('post_message', 'post_image') model = models.Post select_related = ('user',) def form_valid(self, form): self.object = form.save(commit = False) self.object.user = self.request.user self.object.save() return super().form_valid(form) models.py: import misaka class Post(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'posts') posted_at = models.DateTimeField(auto_now = True) post_message = models.TextField() message_html = models.TextField(editable = False) post_image = … -
Clone model object values Django
i want to clone the values from existing model object and sanitize the values for special characters to provide a better search. So i already have values in the database that i want to sanitize and store in a new object after. This is a code example: class Entry(models.Model): headline = models.CharField(max_length=255) sanitized_headline = models.CharField(max_length=255) I would like populate all the sanitized_headline objects with the corresponding headline values after some character replacements like this re.sub('č', 'c', headline) applied to headline before cloning, as well as do this for every new entry. Im using Django for a GraphQl API character replacement can't be done through a view. Thank you -
Whats is the mean of getting {count: 0, next: null, previous: null, results: Array(0)} on console?
I am fetching the data from database in reactjs using axios below the code componentDidMount() { this.setState({ loding: true }); const token = getTokenu(); Axios.get(ApiUrlConstant.getApiFullUrl("bulletin.article"), { headers: { Authorization: "Token " + token, }, }) .then((res) => { console.log(res.data); this.setState({ data: res.data, loding: false }); }) .catch((error) => { this.setState({ error: error, loading: false }); }); } with django backend then I get below log on the console.. {count: 0, next: null, previous: null, results: Array(0)} note:-The data is there in our database. but still Im getting above log on console What is the mean of that? if we have data then why empty array showing on console? -
How to install pscopg2 on Python 3.9?
I have been trying to install psycopg2 (pip install psycopg2), but I keep getting error. I have also tried with: pip install psycopg2-binary but I'm getting the same error. Here is the error message: ERROR: Command errored out with exit status 1: command: 'c:\users\viktor\pycharmprojects\wemport\venv\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Viktor\\AppData\\Local\\Temp\\pip-install-015ceiei\\psycop g2\\setup.py'"'"'; __file__='"'"'C:\\Users\\Viktor\\AppData\\Local\\Temp\\pip-install-015ceiei\\psycopg2\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"' "', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl' cwd: C:\Users\Viktor\AppData\Local\Temp\pip-install-015ceiei\psycopg2\ Complete output (23 lines): running egg_info creating C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info writing C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. How to fix that? -
send_mail() in django is not sending. Command line sendmail is
I have a linux laptop. I am trying to test out some email functionality in my django app and I can't seem to get send_mail or EmailMessage to work. Here is my sendmail: def get(self, request, *args, **kwargs): send_mail( 'Subject here', 'Here is the message.', 'me@pop-os.domain', ['me@gmail.com'], fail_silently=False, ) return HttpResponse('Message sent') When I go to the page it prints a successful email message in the Terminal: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject here From: me@po-pos.domain To: me@gmail.com Date: Mon, 26 Oct 2020 19:13:36 -0000 Message-ID: <160373961632.78488.2486155271127153156@pop-os.localdomain> Here is the message. I never receive the message in my gmail. I've changed to From and To to mask the actual email addresses. What could I be doing wrong? If I use the command line to sendmail like this it works. sendmail user@example.com < /tmp/email.txt -
Circular import error in wagtail.contrib.forms.models
I want to make sure that this is a bug before I submit it and not something I've configured incorrectly. I'm updating a website from Wagtail 2.5 to Wagtail 2.10.2 and I seem to have triggered a circular import into previously working code. The imports are as follows: from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField, StreamField from wagtail.admin.edit_handlers import FieldPanel, FieldRowPanel, MultiFieldPanel, \ InlinePanel, PageChooserPanel, StreamFieldPanel, TabbedInterface, ObjectList from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.documents import get_document_model from wagtail.documents.edit_handlers import DocumentChooserPanel from wagtail.snippets.models import register_snippet from wagtail.search import index from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.contrib.forms.models import AbstractForm, AbstractFormField, AbstractFormSubmission from wagtail.contrib.forms.edit_handlers import FormSubmissionsPanel from wagtail.contrib.forms.views import SubmissionsListView from wagtail.contrib.forms.forms import FormBuilder from wagtail.api import APIField The error I'm getting is: ImportError: cannot import name 'AbstractForm' from partially initialized module 'wagtail.contrib.forms.models' (most likely due to a circular import) I'm having a hard time sorting out where the issue is because it's hitting the import error at the start of the module. One thing I did try was to instead do from wagtail.contrib.forms import models as form_models and then use form_models.ModelName but that also resulted in a circular import error for AbstractFormField. However, that was triggered when the import is actually … -
Django - Is there a way to display a fa icon in a CreateView?
In my page, I have a notification system, which allows the admins to send custom notifications to a certain set of users. For now, it works correctly, creating a Notification object, which is then displayed to the users that need to see it. In my notifications bar in the UI, it displays a list of notifications, ordered by date, and each notification has an icon. For specific notifications (system-level notifications), there's specific fa icons being included <i class="fas fa-handshake"></i>, for instance. I'd like the admins to be able to include a specific icon from a set of icons I set. My relevant models look like this: class Icono(models.Model): name= models.CharField(max_length=100, null=False, blank=False) slug = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return mark_safe('<i class="{}"></i>'.format(self.slug)) class Notificacion(models.Model): icono = models.ForeignKey(Icono, on_delete=models.CASCADE, null=True) # Other attributes I have a CreateView that creates the notification, that looks like this: class FormEnviarNotificacionView(LoginRequiredMixin, SuccessMessageMixin, SetUserEventoFormMixin, CreateView): model = Notificacion form_class = NotificacionForm template_name = 'eventos_admin/enviar_notificacion_a_asistentes.html' def get_success_url(self): return reverse_lazy('eventos_admin:send_notification', kwargs={'pk_evento': self.request.user.evento_activo.id}) def get_success_message(self, cleaned_data): if not self.object: return messages.warning(self.request, 'Hubo un error al enviar la notificación. Por favor, sólo envíe texto.') return 'Mensaje enviado correctamente.' And the form is just this: class NotificacionForm(AgregarNotificacionMixin, forms.ModelForm): class Meta: model … -
How to insert JSON file into django model to create an object
I have a huge json file like this and I cant enter it manually {"idmeasurements":2,"ip":"1.161.137.116","ip_decimal":27363700,"city":"Taipei","country":"Taiwan","latitude":25.04214,"longitude":121.51987,"d_type":null,"dorgtype":"Telecommunications","naics":null,"isic":"Telecommunications","naics_code":517000.0,"isic_code":"J6100","data_source":"02-05-2018\/ddos1.csv","attack_type":"UDP Flood ","magnitude":0.1,"continent":"Asia","region":null,"state":"Taipei","isp":"HiNet","orgm":"HiNet","orgtype":"Telecommunications"} {"idmeasurements":3,"ip":"1.162.55.48","ip_decimal":27408176,"city":"Taipei","country":"Taiwan","latitude":25.04214,"longitude":121.51987,"d_type":null,"dorgtype":"Telecommunications","naics":null,"isic":"Telecommunications","naics_code":517000.0,"isic_code":"J6100","data_source":"02-05-2018\/ddos1.csv","attack_type":"UDP Flood ","magnitude":0.099887,"continent":"Asia","region":null,"state":"Taipei","isp":"HiNet","orgm":"HiNet","orgtype":"Telecommunications"} {"idmeasurements":5,"ip":"1.163.233.221","ip_decimal":27519453,"city":"Sanchong","country":"Taiwan","latitude":25.06667,"longitude":121.5,"d_type":null,"dorgtype":"Telecommunications","naics":null,"isic":"Telecommunications","naics_code":517000.0,"isic_code":"J6100","data_source":"02-05-2018\/ddos1.csv","attack_type":"UDP Flood ","magnitude":0.094098,"continent":"Asia","region":null,"state":"New Taipei","isp":"HiNet","orgm":"HiNet","orgtype":"Telecommunications"} and a model like this class Data(models.Model): idmeasurements=models.IntegerField() ip=models.CharField(max_length=300) ip_decimal=models.IntegerField() city=models.CharField(max_length=300) country=models.CharField(max_length=300) latitude=models.FloatField() longitude=models.FloatField() d_type=models.CharField(max_length=300, null='TRUE') dorgtype=models.CharField(max_length=300) naics=models.CharField(max_length=300, null='TRUE') isic=models.CharField(max_length=300) naics_code=models.IntegerField() isic_code=models.CharField(max_length=300) data_source=models.CharField(max_length=300) attack_type=models.CharField(max_length=300) magnitude=models.FloatField() continent=models.CharField(max_length=300) region=models.CharField(max_length=300) state=models.CharField(max_length=300) isp=models.CharField(max_length=300) orgm=models.CharField(max_length=300) orgtype=models.CharField(max_length=300) I want to save this json data to create an object in this model -
Django WeasyPrint
I have a django template view that generates a bar chart: {% block pagecontent %} <script src="/static/javascript/jslib/highcharts.7.1.1/highcharts.7.1.1.js"></script> ... <link rel="stylesheet" href='/static/semantic/plugins/modal.css'> <h1>Test</h1> <div class="ui padded grid"> <div id="container" style="width:100%; height:400px;"></div> </div> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function () { var mainChart = Highcharts.chart('container', { animation: false, chart: { type: 'bar' }, title: { text: 'Fruit Consumption' }, xAxis: { categories: ['Apples', 'Bananas', 'Oranges'] }, credits: { enabled: false }, yAxis: { title: { text: 'Fruit eaten' } }, series: [{ name: 'Jane', data: [1, 0, 4] }, { name: 'John', data: [5, 7, 3] }] }); }); var demandChart; // globally available document.addEventListener('DOMContentLoaded', function() { demandChart = Highcharts.stockChart('container', { rangeSelector: { selected: 1 }, series: [{ name: 'USD to EUR', data: usdtoeur // predefined JavaScript array }] }); }); </script> {% endblock %} I'm using django-weasyprint to download the file but its not showing the javscript generated content. How can I do this via weasyprint? If its not possible, are there any packages that do support showing javascript content? Here is the weasyprint code: html = render_to_string(template_name=template_name, context=context) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = file_name pdf = weasyprint.HTML(string=html).write_pdf( stylesheets=[ weasyprint.CSS(base_url=base_url, string='body { font-family: Georgia, serif}'), ] ) -
Deploying Django + Next JS
I have built Django + Next JS website and now I want to deploy. I don't know which one to prefer hosting server or VPS. Website is simple, static and kind of catalogue. Next JS default homepage is pages/index.js. I mean it is not index.html, it is index.js Is it possible on hosting server? I'm asking because next js is also need to run node js server on development. On VPS plan does anyone know about how to dockerize exactly this things? Hosting or VPS? Which hosting server do you prefer? -
Calling javascript get from Django template does not fire
I'm trying to implement a simple like functionality on my Django site, should be straightforward enough. All of my code works fine except for the get() statement in the jquery code - it just doesn't do anything. I've looked through as many examples as I can and everything seems legit, but the get code just doesn't fire. I can manually put in the url, I reach my view function fine: the console output and the returning "hello" works when I do this. I've put in a call to update a test field to make sure the script is firing, that's ok. I'm stumped - any help would be greatly appreciated. I've stripped the code down to ensure it's just the .get() left tripping me up: In my template: <strong id="like_count">{%product.likes%}</strong> <button id="likes" data-prodid="{{product.id}}" class="btn btn-primary" type="button"> Like </button> <p id='test'></p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript"> $('#likes').click(function(){ var prodid; prodid = $(this).attr("data-prodid"); $('#test').html(prodid); $.get('/products/like/', {'product_id': prodid}, function(data){ $('#like_count').html(data); }); }) </script> My view function is simply this for the moment: def like_category(request): print('reached like_category') return HttpResponse('hello') Many thanks in advance for help with this. -
Django allauth disable new user creation
I am using Django allauth package I would like to implement the following functionality: If social user exists in my database, I do the usual logging in If there is not such social user, I would like to disallow user creation and return (in my response from view) just the data obtained from social network I understand how to disallow new users sign-up (through is_open_for_signup method), however I cannot figure out, how to return the data, obtained from the social network. Any help with that? -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/learn/learn-coming-soon/ Raised by: learn.views.CourseDetailView
i am trying to make a link on my home page to open another page. i created the template and i added the url path and view but i am still getting a page not found error. please help thanks. then name of the template is learn-coming-soon.html here is the code views.py class LearnComingSoonView(TemplateView): template_name = 'learn-coming-soon.html' urls.py path('learn-coming-soon/', views.LearnComingSoonView.as_view(), name='learn-coming-soon'), template {% extends 'base.html' %} {% load static %} {% block content %} <section id="default" class="hero-learn"> <div class="default"> <div class="hero-deets"> <h1>Coming Soon</h1> <!-- <h1>Learn anytime</h1> <p>become the best version of you today.</p> --> </div> </div> </section> {% endblock %} -
I am getting ValueError at /car/offer/4/ Cannot assign "4": "CarRent.car" must be a "Car" instance. when trying to save Car instance to form
I am working on a car rental website for uber drivers in django, from the detailView I need drivers to be able to choose the duration of their rental, and other information will be auto filled to the form from my views.py, i was able to get the driver through request.user, i also need the PK of the car to be rented. searching through here i’ve tried various suggestions by people here, but i keep getting one error after another… using self.kwargs['pk'] results in ValueError at /car/offer/4/ Cannot assign "4": "CarRent.car" must be a "Car" instance. then i tried using form.car = Car.objects.get(pk= self.kwargs.get('pk')) which results in a AttributeError at /car/offer/4/ 'CarRent' object has no attribute 'is_valid' can someone please tell me how to get the car instance saved in the CarRent model? any help will be greatly appreciated. Thanks below is my code (reduced to the relevant bit) models.py class Car(models.Model): car_owner = models.ForeignKey(User, related_name='car_owner', on_delete=models.CASCADE) class CarRent(models.Model): car = models.ForeignKey(Car, related_name='rented_car', on_delete=models.CASCADE) driver = models.ForeignKey(User, related_name='driver_renting', on_delete=models.CASCADE) rented_weeks = models.BigIntegerField(default=1, choices=WEEK_CHOICES) forms.py class RentForm(forms.ModelForm): class Meta: model = CarRent fields = ['rented_weeks'] i’m only displaying the rented weeks as that’s the only information i need from the user. … -
Django query content_type by name not content_type_id
I need to count some relations from my Flags model to my Post Model. Now I don't understand how to query for the Post model name at my query, I understand how to query for the content_type_id but not for the content_type (as a string). I got something like this on my mind: Q(models.Q(('app_label', 'App'), ('model', 'Post')) but I don't know how the Syntax has to look like at that point, can smb. help? example: def post_list_most_bad_flags(request): p_counter_query = Flags.objects.filter(content_type_id=12) # --> Want to replace this with content_type instead if content_type_id counter = p_counter_query.count() print(counter) Thanks in advance -
Django Channels ASGI - AppRegistryNotReady: Apps aren't loaded yet
Running my project with python manage.py runserver boots it up perfectly using the channels asgi development server, however when running the project with Daphne (daphne project.routing:application) I get the error AppRegistryNotReady: Apps aren't loaded yet. settings.py INSTALLED_APPS = [ 'channels', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', # ... # ... installed apps and custom apps ] WSGI_APPLICATION = 'project.wsgi.application' ASGI_APPLICATION = 'project.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [REDIS_URL], } }, } routing.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.conf.urls import url from my_app.consumers import MyCustomConsumer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter([ url(r'^ws/custom/$', MyCustomConsumer), ]) ), }) I have tried adding django.setup() as described in other questions, as well as running with uvicorn instead of daphne but still getting the same error. I've also tried pointing to the websocket routing in settings.CHANNEL_LAYERS['ROUTING'] and moving the application initialization out to an asgi.py file but no luck there either. I can't tell what I'm doing differently from the channels documentation, any help appreciated. -
Ajax, Django: status 200 but nothing happens
I am trying to post comment with ajax, but it is not working. When I press button console is not printing any error, comment is not being posted. In command line I see: "POST / HTTP/1.1" 200 5572 When I change button to "submit" it is posting and responding with proper JSON like: {"comment": {"id": 16, "author": 1, "content": "test", "post": 12}} My code is below, any help is appreciated: views.py def homepage(request): profiles = Follow.objects.filter(follow_by=request.user.profile).values_list('follow_to', flat=True) posts = Post.objects.filter(author_id__in=profiles).order_by('-date_of_create') if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): pk = request.POST.get('pk') post = Post.objects.get(pk=pk) new_comment = Comment.objects.create( author = request.user.profile, post = post, content = form.cleaned_data['content'] ) return JsonResponse({'comment': model_to_dict(new_comment)}, status=200) form = CommentForm() context = { 'posts': posts, 'form': form } return render(request, 'posts/homepage.html', context=context) template <div class="comments" id="{{ post.pk }}" style="display: none"> {% include 'posts/comments.html' %} <form action="" method="post" class="commentForm" data-url="{% url 'post_comments' post.pk %}"> {% csrf_token %} <input type="hidden" name="pk" value="{{ post.pk }}"> {{ form.as_p }} <button type="button" class="commentBtn" id="{{ post.pk }}">Comment</button> </form> addComment.js $(document).ready(function () { $('.commentBtn').click(function () { let serializedData = $('.commentForm').serialize(); let btn = $(this); let id = btn.attr('id'); console.log(btn); $.ajax({ url: $("commentForm").data('url'), data: serializedData, type: 'post', dataType: 'json', success: function (data) { … -
Django views and requests
How can I catch and process arbitrary request in Django view? For example: def index(request): template_name = 'index.html' users = User.objects.all() return render(request, template_name, {'users': users}) The request parameter here is responsible only for loading the index page, am I right? But how do I process an arbitrary request from front-end, for example, my view has got the data from the database. I need to transfer it to front-end part of my app. How can I do it? Without using context. The request from JS: fetch('index.html', { method: 'GET', }).then(response => response.json()).then(data => console.log(data)) SOMEONE HELP ME I'M TIRED OF SEARCHING THE ANSWER! -
django login form and form validation with ajax in bootstrap modal
i'm new to ajax and i want the user to be able to login with this login form and if the password is incorrect it tells him that signin is invalid without the page being refreshed,the form is contained in a bootstrap modal after checking some answers and some tutorials here is what i tried: i have a normal login form in my forms.py in my views.py signin_form = SigninForm() user = request.user if request.method == "POST": if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) data['email'] = email data['password'] = password data['stat'] = "ok" return JsonResponse(data) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') else: data['stat'] = "error" the form in the template <form action="" method="POST" id="form-signin"> {% csrf_token %} {{signin_form.email}} {{signin_form.password}} <button class="btn btn-success" id="signin-btn" type="submit" name="signin_form">Sign in</button> {% for message in messages %} <div class="alert alert-danger "> {{ message }}</div> {% endfor %} </form> in my js file $(function () { $("#signin-btn").click(function () { $.ajax({ type: 'POST', data: $("#form-signin").serialize(), success: function (data, status) { if (data['stat'] == "ok") { $('#joinus').modal('hide'); } else { $('#joinus').html(data); $('#joinus').modal('show'); } } }); with all this … -
Filtering combobox according to a project list create by logged user in django
I'm new to django and have a lot to learn. I am developing a system in which the logged in user registers his requirement, but each requirement is linked to a project that the same user created. As it is a multi-tenant system, so several users will use the system and each one registers its own project and requirement. I'm having the following message AttributeError at /requisitos/cadastrarRequisito/ 'WSGIRequest' object has no attribute 'projeto' My model (in portuguese) class Requisito (models.Model): nomeRequisito = models.CharField(max_length=30, verbose_name=('Nome do Requisito')) responsavel = models.CharField(max_length=30, verbose_name=('Responsável pelo Desenvolvimento')) código = models.CharField(max_length=20, verbose_name=('Código do Requisito')) projeto = models.ForeignKey(Projeto, on_delete=models.PROTECT) prioridade = models.CharField(max_length=10, verbose_name=('Prioridade do Requisito')) risco = models.CharField(max_length=10, verbose_name=('Risco do Requisito')) motivo = models.CharField(max_length=20, verbose_name=('Motivo do Requisito')) status = models.CharField(max_length=20, verbose_name=('Status do Requisito')) requisitosImpactados = models.CharField(max_length=100, verbose_name=('Requisitos Impactados')) user = models.ForeignKey(User, on_delete=models.CASCADE) estoriaUsuario = HTMLField() regrasNegocio = HTMLField() def __str__(self): return self.nomeRequisito Forms.py class CadastrarRequisitos(ModelForm): def __init__(self, projeto, *args, **kwargs): super(CadastrarRequisitos, self).__init__(*args, **kwargs) self.fields['projeto'].queryset = Projeto.objects.filter( projeto=Projeto.nomeProjeto) class Meta: model = Requisito fields = ['nomeRequisito', 'responsavel', 'código', 'projeto', 'prioridade', 'status', 'risco', 'motivo', 'requisitosImpactados', 'user', 'estoriaUsuario', 'regrasNegocio'] view @method_decorator(login_required, name='dispatch') class RequisitoCreate(CreateView): model = Requisito form_class = CadastrarRequisitos def get_form_kwargs(self): kwargs = super(RequisitoCreate, self).get_form_kwargs() kwargs.update({'projeto': self.request.projeto}) return kwargs … -
django.db.utils.OperationalError: disk I/O error
i made crawling and saving the info to django.db function with multiprocessing. it works fine at first but gives error later. when i launch stockPriceUpdate() on my desktop, it doesn't occur any errors. but when i launch on my laptop, it works fine at first but laters, it's speed slows down and gives error like below. Stock is my django model mycode def stockPriceCrawling(stockTitle): url = 'http://asp1.krx.co.kr/servlet/krx.asp.XMLSiseEng?code=' + str(stockTitle) html = requests.get(url).content soup = BeautifulSoup(html, 'html.parser') stockinfo = soup.select('TBL_StockInfo')[0] price = stockinfo['curjuka'].replace(',','') highestPrice = stockinfo['highjuka'].replace(',','') lowestPrice = stockinfo['lowjuka'].replace(',','') tradeVolume = stockinfo['volume'].replace(',','') tradeValue = stockinfo['money'].replace(',','') print("info : ",' ', price," ",highestPrice," ",lowestPrice," ",tradeVolume," ",tradeValue) db.connections.close_all() stock= Stock.objects.get(code=stockTitle) stock.price = price stock.highestPrice = highestPrice stock.lowestPrice = lowestPrice stock.tradeVolume = tradeVolume stock.tradeValue = tradeValue stock.save() def stockPriceUpdate(process=32): # start = time.time() stocks = Stock.objects.all() stockTitles=[] for stock in stocks: stockTitles.append(str(stock.code)) pool = Pool(32) r=pool.map(stockPriceCrawling, stockTitles) pool.close() pool.join() error Traceback (most recent call last): File "/mnt/c/Users/DAUN/Desktop/swpp/swpp/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/mnt/c/Users/DAUN/Desktop/swpp/swpp/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: disk I/O error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 121, in worker result = (True, func(*args, **kwds)) … -
OperationalError: could not translate host name "db" to address: Unknown host
I have a problem with connecting Django with PostgreSQL installed in docker, when run Django using python manage.py runserver settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'trytofindme', 'HOST': 'db', 'PORT': '5432', } } Dockerfile: # pull official base image FROM python:3.6.4-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install wkhtmltopdf dependencies RUN wget https://s3.amazonaws.com/shopify-managemant-app/wkhtmltopdf-0.9.9-static-amd64.tar.bz2 RUN tar xvjf wkhtmltopdf-0.9.9-static-amd64.tar.bz2 RUN mv wkhtmltopdf-amd64 /usr/local/bin/wkhtmltopdf RUN chmod +x /usr/local/bin/wkhtmltopdf # install python dependencies RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app/requirements.txt RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev && \ python3 -m pip install -r requirements.txt --no-cache-dir && \ apk --purge del .build-deps # copy project COPY . /usr/src/app/ docker-compose: version: '3.7' services: db: image: postgres:13.0 restart: always environment: POSTGRES_PASSWORD: trytofindme ports: - 15432:5432 adminer: image: adminer restart: always ports: - 8020:8080 I can't find mistake in my code. Are there any variant to connect PostgreSQL and Django, not loosing the protection? I used: docker-compose … -
Automatic generate data in table when migrate in Django
Is there any way how can I add automatically data in tables when using command migrations in Django? Let say I have usertype_tbl every time I use command makemigrations in Django it should store automatically this data - Admin, Super admin, other_user etc. in usertype_tbl. Is there any way how to implement this? thanks for the help in advance! models.py class usertypes_tbl(models.Model): user_type = models.CharField(max_length=264) description = models.CharField(max_length=264) status = models.CharField(max_length=264) //add some data = Admin, Super_admin , etc. -
How to Create a storage folder using User name and id in django restfull api
I have a video file that is uploaded by a user, I want to create a separate folder in the media/Smat/name/id directory by using the name and id of the uploaded file. model.py from django.db import models from datetime import datetime import cv2 import tempfile # from .utils import get_uploaded_video from django.utils import timezone import os def upload_to(instance, filename): now = timezone.now() base, extension = os.path.splitext(filename.lower()) return f"Smat/{now:%Y-%m-%d}" class MyVideo(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to=upload_to, null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) seriliazer.py from rest_framework import serializers from .models import MyVideo from django.contrib.auth.models import User class MyVideoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyVideo fields = fields = ['id', 'url', 'name', 'date', 'videofile'] class UploadVideoSerializer(serializers.ModelSerializer): class Meta: model = MyVideo fields = ['videofile'] -
Django REST API nested values updated if exists
I have a Django project where I have a table for Projects, Customers and Contact Persons. Projects have a foreign key to both Customers and Contact Persons, and Contact Persons have a foregin key with Customers. I am using Django REST API to get the data from the server, and when I get a project instance, I would like to be able to see contact persons fields (at least some of them), and when I create/update a Project, I should be able to include a contact person. If the contact person does not exist, it should be created, if it does exist, it might be updated. I have been trying to use Djangos "update_or_create", however, if the contact person already exists, I get a response with "contact person with this name already exists." before I even get into my create function. Any idea why this is happening? Project View: class ProjectViewSet(ModelViewSet): queryset = Project.objects.all() serializer_class = ProjectSerializer example of ProjectSerializer class class ProjectSerializer(DynamicFieldsModelSerializer, ModelSerializer): contact_person = ContactPersonSerializer(required=False) class Meta: model = Project fields = '__all__' def to_representation(self, instance): if instance.customer: rep['customer'] = instance.customer.name return rep def create(self, validated_data): contact_person = validated_data.pop('contact_person') contact_person, created = ContactPerson.objects.update_or_create(name=contact_person['name'], defaults={'phone': contact_person['phone'], 'customer': Customer.objects.get(pk=contact_person['customer'].id)}) project …