Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Database Creation in PyTest not working with Generator Error
I am running into an issue with PyTest that I cannot seem to diagnose. I am setting up a staging environment and running tests on a remote DB and when PyTest is run I get: RuntimeError: generator didn't stop Here is the full traceback: ================================================================================================================ ERRORS ================================================================================================================ ________________________________________________________________________________________ ERROR at setup of TestLoginStaff.test_can_login_staff _________________________________________________________________________________________ request = <SubRequest 'django_db_setup' for <Function test_can_login_staff>>, django_test_environment = None, django_db_blocker = <pytest_django.plugin._DatabaseBlocker object at 0x7f476cfb8490>, django_db_use_migrations = True django_db_keepdb = True, django_db_createdb = False, django_db_modify_db_settings = None @pytest.fixture(scope="session") def django_db_setup( request, django_test_environment, django_db_blocker, django_db_use_migrations, django_db_keepdb, django_db_createdb, django_db_modify_db_settings, ): """Top level fixture to ensure test databases are available""" from django.test.utils import setup_databases, teardown_databases setup_databases_args = {} if not django_db_use_migrations: _disable_native_migrations() if django_db_keepdb and not django_db_createdb: setup_databases_args["keepdb"] = True with django_db_blocker.unblock(): > db_cfg = setup_databases( verbosity=request.config.option.verbose, interactive=False, **setup_databases_args ) /usr/local/lib/python3.8/site-packages/pytest_django/fixtures.py:105: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
The default profile that i have put in the image field doesn't work in Django
I have a Custom User model which has an image field, I have as well added a default option and have given a default option but the user doesn't seem to be using the default option anytime I render it onto the templates. I have observed that only when I add an image onto it, it works but it doesn't use the default if there is not image in it. This is the file structure/directory in case I am making some mistakes there settings.py STATIC_URL = 'static/' STATIC_ROOT = 'staticfiles/' STATICFILES_DIRS = [BASE_DIR / 'static'] MEDIA_URL = 'media/' MEDIA_ROOT = 'media/' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) image = models.ImageField(upload_to='images/users', blank=True, null=True, default='images/users/profile-pixs.png') templates.html <div class="image"> <a href="#"> <img src="{{request.user.image.url}}" alt="John Doe" /> </a> </div> -
ConnectionRefusedError while sending email through gmail using Django
I am trying to send e-mails through my Gmail account for my Django application. I'm using below configurations in settings.py file. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'username@gmail.com' EMAiL_HOST = 'smtp-relay.gmail.com' # tried smtp-relay.gmail.com also EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = 'Gmail password / app password' Import statements in this regard: from django.core.mail import send_mail, EmailMessage from django.conf import settings Following is in my views function: message = EmailMessage(subject=email_subject, body=email_message, from_email=settings.EMAIL_HOST_USER, to=[email, 'username@gmail.com']) message.send(fail_silently=False) I have tried this also: send_mail(email_subject, email_message , settings.EMAIL_HOST_USER, [email, 'username@gmail.com'] , fail_silently=False, ) Any help is much appreciated. Please note that I have tried: enabling less secure apps button in Gmail Then, I disabled less secure apps, enabled 2 factor authentication and use app passwords option of Google. -
Django Models - Lead Model
Good day. I am busy with a small project on creating a django leads crm. The first user story is as follows: When a user logs onto the website - they will complete a short form. Once submitted all leads will be sent to a default (listview) showing all leads. Leads will then be allocated by the manager to individual agents. As such leads will have an initial(default category) of 0 i.e. is_unassigned, once assigned the lead_category must change to 1 i.e. is_assigned. This can be either int type fields or just boolean fields. What would be the best representation of this model? This is the current model I have. models.py class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) lead_source = models.CharField(max_length=20, null=True) def __str__(self): return f{self.first_name} {self.last_name} class LeadAssigned(models.Model): pass Is it best that I create a boolean field or would I create a seperate model showing LeadAssigned? -
Django Suspicious File Operation when including ReactJS's build/static in STATICFILES_DIRS
My settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build', 'static'), os.path.join(BASE_DIR, 'src/static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I'm following this guide to put my app on heroku, but I'm running into problem when doing python manage.py collectstatic The error is: django.core.exceptions.SuspiciousFileOperation: The joined path (/path/to/root_folder/static/media/file.jpg) is located outside of the base path component (/path/to/root_folder/staticfiles) What's strange is that there's no place that mentions static/media in my app, except in the build/asset-manifest.json and some css files in static/css/ I'm wondering how the /path/to/root_folder/static/media/ is from and how to fix it None of the previous posts I've found solve my problem. If you can link one, that'd be great too -
Why request.user == 'admin' conditional statement not working in Django3 views.py?
I am currently logged as 'admin' in my django3 project. As 'admin', I have to display all the books. But the if-else statement in the views.py is not recognising the 'admin' and always goes into the else section of the conditional statement. def book_list(request): print ('Currently logged as ', request.user) if request.user is 'admin': print ('All') books = Book.objects.all() else: print ('Filter') books = Book.objects.filter(author=request.user) return render(request, 'mtsAuthor/book_list.html', { 'books': books }) When I refresh the page as an 'admin', the following custom debug messages are seen in the terminal. Hope the same shall help to troubleshoot. Currently logged as admin Filter [25/Feb/2021 13:39:45] "GET /mtsAuthor/books/ HTTP/1.1" 200 9363 [25/Feb/2021 13:39:45] "GET /media/books/covers/_DSC0179.jpg HTTP/1.1" 304 0 -
Django language_cookie domain cannot be changed
So there is a poroblem. I need to change domain for my site until I use eg. ab.user.localhost ac.user.localhost My language cookie with default name 'django_language' has domain accordingly set to host: ab.user.localhost or ac.user.localhost depends on which of these two urls you currently are. I want to have this cookie domain set for all subdomains to: .user.localhost So I used in my django settings.py like https://docs.djangoproject.com/en/2.2/ref/settings/#language-cookie-domain LANGUAGE_COOKIE_DOMAIN = '.user.localhost' But still.. After clearing cookies django_language cookie has ab.user.localhost domain or ac.user.localhost domain set. Any idea why this is not working? -
Django-allauth - Custom Sign Up with OneToOneField
I created a sign up form using two grouped forms and it has been working perfectly, but I would like to use django-allauth because of the features (login only with e-mail, sending confirmation e-mail ...). However even reading some topics I still couldn't. forms.py class ExtendedUserCreationForm(UserCreationForm): email = forms.EmailField(required=True, label="E-mail") first_name = forms.CharField(max_length=30, label="Nome") last_name = forms.CharField(max_length=30, label="Sobrenome") class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('sexo', 'data_nascimento', 'foto', 'sobre_mim', 'telefone', 'paroquia', 'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram') CIDADES = [] for i in cidadesReader: if i[1] not in CIDADES: CIDADES.append(i[1]) widgets = { 'cidade': floppyforms.widgets.Input(datalist=CIDADES, attrs={'autocomplete': 'off'}), } views.py def signup(request): if request.method == 'POST': form = ExtendedUserCreationForm(request.POST) profile_form = UserProfileForm(request.POST, request.FILES) if form.is_valid() and profile_form.is_valid(): user = form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) #login(request, user) return redirect('home') else: form = ExtendedUserCreationForm() profile_form = UserProfileForm() context = {'form': form, 'profile_form' : profile_form} return render(request, 'registration/signup.html', context) signup.html {% extends '_base.html' %} {% load crispy_forms_tags … -
how can tranlslate dango lazy translte
hellow my friends i am use jango and lazy translation as __() but i can't translte this file result = [{"content":'{"index":44,"list":{"3":{"id":3,"type":"box3","setting":{"setTitle":"","setColor":"box-default"}},"4":{"id":4,"type":"box3","setting":{"setTitle":"","setColor":"box-default"}},"5":{"id":5,"type":"box3","setting":{"setTitle":"","setColor":"box-default"}},"6":{"id":6,"type":"box3","setting":{"setTitle":"","setColor":"box-default"}},"7":{"id":7,"type":"box12","setting":{"setTitle":"全球產量分布","setColor":"box-primary"}},"9":{"id":9,"type":"box4","setting":{"setTitle":"","setColor":"box-default"}},"10":{"id":10,"type":"box4","setting":{"setTitle":"","setColor":"box-default"}},"11":{"id":11,"type":"box4","setting":{"setTitle":"","setColor":"box-default"}},"12":{"id":12,"type":"box4","setting":{"setTitle":"","setColor":"box-default"}},"15":{"id":15,"type":"word","setting":{"setTitle":"","setTip":"","setIcon":"fa fa-file-text","setColor":"bg-blue","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"16":{"id":16,"type":"word","setting":{"setTitle":"","setTip":"","setIcon":"fa fa-envelope","setColor":"bg-yellow","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"17":{"id":17,"type":"word","setting":{"setTitle":"","setTip":"","setIcon":"fa fa-thumbs-up","setColor":"bg-green","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"18":{"id":18,"type":"word","setting":{"setTitle":"","setTip":"","setIcon":"fa fa-line-chart","setColor":"bg-red","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"20":{"id":20,"type":"meter-bar","setting":{"setTitle":"","setTip":"台北","setColor":"progress-bar-blue","setMax":"100","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"21":{"id":21,"type":"meter-bar","setting":{"setTitle":"","setTip":"東京","setColor":"progress-bar-aqua","setMax":"100","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"22":{"id":22,"type":"meter-bar","setting":{"setTitle":"","setTip":"首爾","setColor":"progress-bar-green","setMax":"100","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"23":{"id":23,"type":"meter-bar","setting":{"setTitle":"","setTip":"紐約","setColor":"progress-bar-yellow","setMax":"100","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"24":{"id":24,"type":"meter-bar","setting":{"setTitle":"","setTip":"曼谷","setColor":"progress-bar-red","setMax":"100","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"25":{"id":25,"type":"meter-bar","setting":{"setTitle":"","setTip":"新加坡","setColor":"color-purple","setMax":"100","setUnit":"單位","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"26":{"id":26,"type":"tube","setting":{"setTitle":"","setTip":"","setIcon":"fa fa-heartbeat","setColor":"bg-red","setUnit":"單位","setMax":"100","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"27":{"id":27,"type":"tube","setting":{"setTitle":"","setTip":"","setIcon":"fa fa-leaf","setColor":"bg-green","setUnit":"單位","setMax":"100","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"28":{"id":28,"type":"tube","setting":{"setTitle":"","setTip":"","setIcon":"fa fa-car","setColor":"bg-blue","setUnit":"單位","setMax":"100","setForm":"","setColumn":[""],"setTime":"all","setType":["static"]}},"30":{"id":30,"type":"bar","setting":{"setTitle":"","setColor":"1","setHeight":"240","setYstart":"0","setForm":"","setColumn":[""],"setTime":"all","setType":["static"],"setGroup":[""]}},"31":{"id":31,"type":"box12","setting":{"setTitle":"","setColor":"box-default"}},"39":{"id":39,"type":"box4","setting":{"setTitle":"","setColor":"box-default"}},"40":{"id":40,"type":"box4","setting":{"setTitle":"","setColor":"box-default"}},"41":{"id":41,"type":"pie","setting":{"setTitle":"","setColor":"0","setUnit":"","setHeight":"320","setForm":"","setColumn":[""],"setTime":"all","setType":["static"],"setGroup":[""]}},"43":{"id":43,"type":"pie","setting":{"setTitle":"","setColor":"3","setUnit":"","setHeight":"320","setForm":"","setColumn":[""],"setTime":"all","setType":["static"],"setGroup":[""]}}},"tree":[{"id":"3","tree":[{"id":"15"}]},{"id":"4","tree":[{"id":"17"}]},{"id":"5","tree":[{"id":"16"}]},{"id":"6","tree":[{"id":"18"}]},{"id":"7","tree":[{"id":"9","tree":[{"id":"20"},{"id":"21"},{"id":"22"},{"id":"23"},{"id":"24"},{"id":"25"}]},{"id":"40","tree":[{"id":"41"}]},{"id":"39","tree":[{"id":"43"}]}]},{"id":"10","tree":[{"id":"26"}]},{"id":"11","tree":[{"id":"27"}]},{"id":"12","tree":[{"id":"28"}]},{"id":"31","tree":[{"id":"30"}]}]}'}] how can do it -
what is wrong with my cord(upload file to django)
What's wrong with my code.. it is just upload file to django i read django document and followed the same.. i think.. maybe.. model.py class OverWriteStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): if self.exists(name): os.remove("C:\...\_media/excel", name) return name class Upload(models.Model): title = models.CharField(max_length=30, null=True, blank=True) file_upload = models.FileField(upload_to='excel/', blank=True, storage=OverWriteStorage()) def __str__(self): return self.title forms.py class ModelUpload(forms.ModelForm): class Meta: model = Upload fields = ['title','file_upload'] view.py def excel(request): if request.method == 'POST': form = ModelUpload(request.POST, request.FILES) if form.is_valid(): # file is saved form.save() return HttpResponseRedirect('/success/url/') else: form = ModelUpload() excelTemp = dict(excel['tag'].value_counts().sort_index()) return render(request, 'single_pages/excel.html',{ 'form': form, 'excelTemp': excelTemp, }) my html <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form | crispy}} <button name="choice" value="{{ upload.file }}">upload</button> my wrong message : TypeError at /excel/ join() argument must be str, bytes, or os.PathLike object, not 'NoneType' During handling of the above exception (expected str, bytes or os.PathLike object, not NoneType), another exception occurred: form.save() Please have mercy.. thanks.. -
How to populate html input in Django framework without using a any of Django form?
I'm implementing an HTML table that is populated with information as the page is rendered. I cannot use a form here but still, I need to embed some common input controls to certain s in that HTML table (selection boxes). So I think the data itself can be passed to the template as the page is being rendered but do I need to use javascript to fill the controls? I think I cannot use anything related to forms here. I have implemented a javascript ajax code to get the data when the table is filled by a user. That is working perfectly. But the user does not fill everything on that table but there must be some selections done before the data can be submitted. That data is read from the database, delivered to the HTML table for the user to make a selection. But I have never used HTML inputs other than in Django forms. Or is there a better solution to achieve this? -
Install Postgis and Postgres for Django (windows)
I'm trying to use Postgis along with my Django website and Postgres database. I got Postgis, Django and Postgres installed already on my Windows 10 setup. Now whenever I attempt to run a 'makemigrations' for my models making use of types such as 'Geometry' I got errors saying it's unable to find GDAL. I understand from the documentation you have to install 3 packages before being able to use Postgis; GEOS, PROJ.4 and GDAL. Is this necessary? Whenever I look at the installation guide it seems to be for Linux systems and there's no mention of Windows 10. I'm able to perfectly fine use my databases through the pgadmin interface with Postgis to plot and view lines etc, but Django wont play ball. Does anyone have an idea how to make Postgis work for Django, or do I have to switch to Linux to get the required packages even though I already have them installed through pip installer. Any help is appreciated. Thanks -
Django Admin overwrite the __str__ method in an autocomplete_field
I want to overwrite the __str__ method in Django admin when using the autocomplete_fields = () but the returned values are using __str__. I have a form something like class MyAdminForm(forms.ModelForm): placement = forms.Select( choices = Organisation.objects.active(), ) class Meta: model = Lead fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['placement'].label_from_instance = lambda obj: f'{str(obj)} {obj.post_code}' This will provide back a Select with the organisation name and post code in the dropdown fields. But there are some 80k choices so I need to using autocomplete. Within within admin.py I have class LeadAdmin(admin.ModelAdmin): form = LeadAdminForm autocomplete_fields = ('placement',) As soon as I add the autocomplete_fields I lose my postcode and it reverts to just showing the __str__ Hoa can I used autocomplete_fields and overwrite the __str__ method? -
Is there any/proper method to edit heroku files?
I have an ImportError caused by wagtail-experiments when running heroku run python manage.py migrate reporting that it cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'. During the dev process I changed that to from six import python_2_unicode_compatible so I can use it locally without this error, but heroku installs a new copy and the error is back. My question is, how can I make these types of edits or I'm going to have to contact heroku -
Multiple input fields in in django admin model
I need help to show input fields correspond to each checkbox in Django admin site. I am using Django multiselectinput dependency to show these checkboxes. Image -
Django Authenticate method not working on User class which extends "AbstractUser"
It is a simple view, i have made the following model for users of the college website: class User(AbstractUser): year = models.IntegerField(validators=[MaxValueValidator(4), MinValueValidator(1)], blank=False) Branch_CHOICES = ( ('1', 'CSE'), ('2', 'ECE'), ('3', 'IT') ) branch = models.CharField(max_length=3, choices=Branch_CHOICES) rollNo = models.CharField(validators=[MinLengthValidator(5)], max_length=5, unique=True) In case needed for reference,this is how i am registering the user (The redirect URL returned successfully logs in the user, but when i log out and try to log in back, the authentication fails): def register(request): if request.method == "POST": username = request.POST["username"] rollno = request.POST["rollNo"] year = request.POST["Year"] form = registerForm(request.POST) if form.is_valid(): branch = form.cleaned_data['branch'] else: return render(request, "events/register.html", { "message": "You didn't provide all the fields", "form": registerForm() }) email = str(rollno) + '@iiitu.ac.in' # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "events/register.html", { "message": "Passwords must match.", "form": registerForm() }) if not username or not rollno or not year or not password: return render(request, "events/register.html", { "message": "Please enter all the fields", "form": registerForm() }) # Attempt to create new user try: user = User.objects.create_user(username, email, password) user.rollNo = rollno user.branch = branch user.year = year user.save() except IntegrityError: return render(request, "events/register.html", { … -
DRF: get_object in action from custom queryset
I have ViewSet like this class CustomViewSet( RouteActionArgumentsMixin, viewsets.ModelViewSet ): serializer_class = MySerializer def get_queryset(self): MyModel.objects.filter(...) I want to add an action in this particular ViewSet which is based on the other queryset (let's say it is based on all MyModel objects). @action( detail=True, methods=['post'], serializer_class=OtherSerializer ) def make_action(self, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=self.request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) How can I retrieve self.get_object() based on all MyModel objects? Can I change queryset for this particular action? -
Set default option in select element and load data
On my html-template I got a select-element looking like this: <select class ="form-control", id="categories"> {% for c in categories %} <option value = {{c.id_category}}>{{c}}</option> {% endfor %} </select> Where the user can choose one of the avaiable categories and with javascript the according database entries of that category get loaded in to a table on the site. $(document).ready(function(){ $("#categories").change(function(e){ ... The script only gets active when one uses the dropdown menu. At the moment if you first access the site no data will be shown by default. What I want it to do though is, that by default one of the categories (doesnt really matter which) is selected and the corresponding data is shown. If I simply use 'selected' for one of the options no data will be in the table (obviously, cause the JS doesnt register a change of a selected option). So how can I do this? -
django test failed to start in gitlab ci
i used docker and django for this project and gitlab ci/cd pipleline and test wont even start and exit below error: tests was running until i add some tests in django app and after that it failed. django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known here is my Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ my docker-compose.yml: version: "3.9" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db and my gitlab-ci.yml: image: python:latest services: - mysql:latest - postgres:latest variables: POSTGRES_DB: postgres cache: paths: - ~/.cache/pip/ test: variables: DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB" script: - pip install -r requirements.txt - python manage.py test build: image: docker:19.03.12 stage: build services: - docker:19.03.12-dind variables: IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY - docker build -t $IMAGE_TAG . - docker push $IMAGE_TAG -
Django channels - how to send messages to groups from an external script?
I have a very simple Django channels consumer that subscribes clients to a group: class TestConsumer(AsyncJsonWebsocketConsumer): async def websocket_connect(self, event): await self.accept() await self.send_json('Connected') await self.channel_layer.group_add( 'GROUP1', self.channel_name ) async def websocket_receive(self, event): pass async def websocket_disconnect(self, event): await self.channel_layer.group_discard( 'GROUP1', self.channel_name ) And then, in the same server but outside of the Django application, i have a script that receives data from a websocket server: import asyncio import websockets async def hello(): uri = "ws://SOME-URL" async with websockets.connect(uri) as websocket: data = await websocket.recv() print(json.loads(data)) Is there any way i can send the data received in the second script to users subscribed to GROUP1 in the Django Channels app? So basically every time the second script receives a new message, that message must be sent from the Django Channels app to its clients. For various reasons i can't run the second script in a Django management command, is there another way to do this? -
Issue while compilng java code from django
I am new to django web development currently i am trying to create online java compiler using django which consists of two fields i.e code(we can write our own logic) and inputfield(we can provide our own input field) in this process i am facing issue while executing java program with below code here is my code and i am using python 2.7 and django 1.8 import re import os from django.shortcuts import render from django.http import HttpResponse from .forms import GetForm import subprocess def index(request): if request.method=="GET": form=GetForm() return render(request,'compile.html',{'form':form}) else: form =GetForm(request.POST) if form.is_valid(): main_class_name="" text=form.cleaned_data["code"] // here main_class_name holds main class java name for i in re.split('class ',text)[1:]: if re.search('public static void main',i): main_class_name=re.search('(\w*)',i).group(1) os.chdir('/home/miracle/Desktop/onlineproject/projectCompiler/javacompile/') sd=open(main_class_name+".java","a") sd.write(text) proc = subprocess.Popen(['javac',main_class_name+'.java'],stdin=subprocess.PIPE, stdout=subprocess.PIPE) cmd=['java', main_class_name] output =subprocess.check_output(cmd,shell=True, stdin=subprocess.PIPE,stderr=subprocess.PIPE) form.save() return render(request,'compile.html',{'form1':text}) #My issue My issue is i am able to compile and generate the .class file using above python script but i am unable to run the java code using "java classname" using above python script and also i am not getting any error while executing the above code please help me -
Pls help for django - reply system [closed]
I want to comment - reply system Code: https://pastebin.pl/view/1f67e33d -
Cannot fix unboundlocalError in my Django view
So I have a view that is giving me "UnboundLocalError at /local variable 'word1' referenced before assignment". I have searched for other similar questions and I have tried to change the indentation but the problem won't fix. Can anyone tell me what's the problem? Help is much appreciated. My views.py: def index(request): form = WordForm(request.POST) if form.is_valid(): word1 = form.cleaned_data['Word1'] word2 = form.cleaned_data['Word2'] word3 = form.cleaned_data['Word3'] result = form.cleaned_data['Result'] context = {'form': form, 'word1': word1, 'word2': word2, 'word3': word3, 'result': result} return render(request, 'form.html', context) -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__post_user_post.user_id error after migrat
I try to add postUser field to my existing models. When I tried to migrate, I am getting an error :django.db.utils.IntegrityError: NOT NULL constraint failed: new__post_user_post.user_id This is my model.py from django.contrib.auth.models import User from django.db import models from django.urls import reverse class TaskCategory(models.Model): category_title = models.CharField(max_length=50) def __str__(self): return self.category_title class Post(models.Model): postUser = models.ForeignKey(User,on_delete=models.CASCADE) **I try to add this fild** task_title = models.CharField(max_length=250) task_discription = models.CharField(max_length=250) task_category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) recommended_tools = models.CharField(max_length=250) budget = models.IntegerField(default=0) def __str__(self): return self.task_title + ' | ' + self.task_discription + ' | ' + str(self.task_category) + ' | ' + self.recommended_tools + ' | ' + str(self.budget) + ' | ' + str(self.id) def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) ****Before I added one user, I already had admin and a number of posts created without postUser. Now in User table a have two users admin and one user. When I run makemigrations, I was asked: C:\Users\Davor\Desktop\suit>python manage.py makemigrations You are trying to change the nullable field 'postUser' on post to non-nullable without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows … -
What is the easiest way to do a "promote comment" feature in django
I have blog in Django, where I want to display the promoted content for 24 hrs on top of the page for example there are 100 contents in the blog now the top 10 contents are listed in descending date order in the home page. now out of 100 contents if any one is selected has Feature , I want to add include it in the above list . and it should disappear after 24 hrs. how to achieve this with out using schedulers> is that possible