Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to edit views.py in django when installed in ubuntu server
I installed Django in ubuntu server ,when I connect t my public server:8080 I got Django installed, now how to edit urls.py file or tests.py in server, should I use WinSCP or is there any graphical option to edit files in server to modify Django website -
please help i dont understand
hi please help me i created a createview class in my app and then i put a post method and then it gives me this error: 'Register' object has no attribute 'object' class Register(CreateView): form_class = RegForm model = Users template_name = 'registro.html' success_url = '/home/' def get_form(self, form_class=RegForm): if form_class is RegForm: form_class = self.get_form_class() return form_class(**self.get_form_kwargs()) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): name = form.cleaned_data['name'] Flastname = form.cleaned_data['Fatherslname'] Mlastname = form.cleaned_data['Motherslname'] age = form.cleaned_data['age'] return self.form_valid(form) else: return self.form_invalid(form) and this is my forms i dont know why: class RegForm(ModelForm): class Meta: model = Users fields = ['name', 'lname1'] Name = forms.CharField(label="Nombre", max_length=100, required=False) Fatherslname = forms.CharField(max_length=100, required=False) Motherslname = forms.CharField(max_length=100, required=True) age = forms.IntegerField() UserName = forms.CharField(required=True, max_length=80) userType = forms.ChoiceField(label="Eres?", choices=users) birthplace = forms.ChoiceField(label="Pais", choices=Paises) dateOfBirth = forms.DateField(label="Fecha de Nacimiento", initial=datetime.date.today) imagen = forms.ImageField(label="foto") Email = forms.EmailField(required=True) passwd = forms.CharField(label="contraseña", max_length=32, widget=forms.PasswordInput) ConfPasswd = forms.CharField(label="confirmar contraseña", max_length=100, widget=forms.PasswordInput) -
WebSocket not connecting |. Django Channels | WebSocket
I am using the WebsocketConsumer consumer and when I disconnect the websocket connection it gives the below error. Also when I have already one open connection and when I try to create a connection with the same route it gets Disconnected and gives the same Application instance <Task pending name='Task-5' coro=<StaticFilesWrapper.__call__() running at /Volumes/Data/Projects/LocoNav-LM/vt-lm-server/venv/lib/python3.8/site-packages/channels/staticfiles.py:44> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/futures.py:360, <TaskWakeupMethWrapper object at 0x1076a2580>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 54789] path=b'/ws/users/'> took too long to shut down and was killed. My code:- class TestMultipleUsers(WebsocketConsumer): def connect(self): logging.info('connecting....') self.accept() redis_client = RedisClient(host='localhost', port=6379, db=0) redis_client.subscribe_and_listen() redis_client.subscribe_channel('test') for message in redis_client.sub.listen(): if message is not None and isinstance(message, dict): print(message) self.send(text_data="1") def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) def disconnect(self, close_code): logging.info('disconnecting....') logging.info(close_code) However, whenever I disconnect the web socket from Postman the disconnect method never gets called. requirements.txt channels==3.0.4 Django==4.0 celery==5.2.3 -
Django How to find context data in form_valid when it is not part of the form
I have a forms.Form that just displays a ModelMultipleChoiceField and returns the choice. In the template that holds that form I display the patient information. I obtain that information in get_context_data but I cannot access any patient information once I am in form_valid. The form.cleaned_data only includes the choice from the Form. I need the information from the context to create the necessary table rows using the choice data. class OrderTestsView(FormView): """ """ model = Universal_Test_File form_class = TestOrderForm success_url = '/list_tests/' template_name = "lab/order_tests.html" def get_context_data(self, *args, **kwargs): patient = get_object_or_404(Patient, pk=self.kwargs['pk']) context = super(OrderTestsView, self).get_context_data(**kwargs) context['patient'] = patient return context ### I need to build tables using patient inforamtion along with the choice right here ### but that information, which I have in get_context_data can't be accessed from here def form_valid(self, form): choice = form.cleaned_data.get("choice") if choice: for test in choice: print(test.service_id, test.test_name) return super().form_valid(form) class TestOrderForm(forms.Form): choice = forms.ModelMultipleChoiceField( Universal_Test_File.objects.all().order_by('test_name'), to_field_name="service_id") -
Django admin looks fine, untill I open category. Then overlapping
I have a pretty basic django install, with summernote. When I'm in the admin panel, it looks like so. But when I go to any of the category pages, it looks like this. I tried clearing cache, but still looks the same. Any help would be appreciated. EDIT: My models code is from django.db import models from django.contrib.auth.models import User from django.utils import timezone import uuid STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blog_posts" ) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("post_detail", kwargs={"slug": str(self.slug)}) def get_previous_by_created_on_active(self): return self.get_previous_by_created_on(status=1) def get_next_by_created_on_active(self): return self.get_next_by_created_on(status=1) class Newsletter(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(null=False, blank=True, max_length=200, unique=True) conf_num = models.CharField(max_length=15) confirmed = models.BooleanField(default=False) def __str__(self): return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)" -
Using DRF to update the whole of an object, including nested object
If I have models that look roughly like this:- class Event(models.Model): title = models.CharField(max_length=200) venue = models.ForeignKey(Venue, on_delete=models.PROTECT) class Venue(models.Model): # all of this information comes from the Google Places API place_id = models.CharField(max_length=200) name = models.CharField(max_length=200) address = models.TextField() and I want to be able to update the venue name of an existing event using Django Rest Framework, it looks like I have to write an update() method for my model serializer. I've written it like this:- class EventSerializer(serializers.ModelSerializer): venue = VenueSerializer() class Meta: model = Event fields = ["title", "venue"] def update(self, instance, validated_data): venue_data = validated_data.pop("venue", None) event = super().update(instance, validated_data) if venue_data: venue, _ = Venue.objects.get_or_create( place_id=venue_data["place_id"], defaults={ "name": venue_data["name"], "address": venue_data["address"] }, ) event.venue = venue event.save() return event Does that look like I'm going in the right direction here? I don't want to create a new venue every time someone updates an event - if the place ID is the same as an existing one, I want to reuse it. This code looks a bit cumbersome to me (I've got some very similar looking code in the create() method of the serializer) so I'm just worried that there's an easier, more concise way to … -
Can someone help me with this error (its is from manage.py make migrations):
Click here to see the error it really helps I am new to this, please someone help -
django.db.utils.OperationalError: near "CASCADE": syntax error when making a pull request in Github
I'm trying to deploy a django website with Heroku. When I run python3 manage.py runserver, everything works normally. But when I push it to github and make a pull request, I have an action that tests my code and I run into that error. Using existing test database for alias 'default'... Found 7 test(s). System check identified no issues (0 silenced). ....... Alicia ---------------------------------------------------------------------- Tiffany Barbara Ran 7 tests in 1.319s OK Taylor Dr. Wanda Jacob Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 414, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: near "CASCADE": syntax error The above exception was the direct cause of the following exception: 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 "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/commands/test.py", line 59, in handle failures = test_runner.run_tests(test_labels) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/test/runner.py", line 941, in run_tests self.teardown_databases(old_config) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django_on_heroku/core.py", line 33, in teardown_databases self._wipe_tables(connection) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django_on_heroku/core.py", line 27, in … -
Print button in Django Admin
How to add print button into the Django admin panel, which prints only selected items of the model? my model.py class Student(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) class StudentAdmin( SimpleHistoryAdmin): list_display = ('id', 'name', 'lastname') list_filter = ('lastname',) search_fields = ['name', 'lastname'] history_list_display = ('name', 'lastname') def changed_fields(self, obj): fields = '' if obj.prev_record: delta = obj.diff_against(obj.prev_record) for change in delta.changes: fields += str("{} changed from {} to {} >>> ".format(change.field, change.old, change.new)) return fields return None my admin.py from django.contrib import admin from .models import * admin.site.register(Student, StudentAdmin) -
How can I build a user wallet application in Django?
I want users to be able to pay for goods and services on my Django site using site wallet credits -
How to display GeoJSON on Cesium
I've a Django app that lets you run a spatial query and displays the result in the form of a GeoJSON polygon on a Leaflet map. Here's how I did it on Leaflet: I took the geometry that's stored in the geo_json object in the views.py file, then I added that in the Leaflet map in the geometry.html file through L.geoJSON({{ geo_json | safe }}).addTo(map);. views.py def GetGeometry(request, *args, **kwargs): try: x = request.GET.get('x') y = request.GET.get('y') connection = psycopg2.connect(database="xxx",user="xxx", password="xxx", host="xxx") cursor = connection.cursor() cursor.execute("SELECT xxx From xxx WHERE ST_Intersects(ST_PointFromText('POINT({} {})',4326), geom);".format(x, y)) result=cursor.fetchone() geo_json={ "type": "Feature", "geometry": json.loads(result) } return render(request ,'results/geometry.html', {'geo_json': geo_json }) except: return render(request ,'results/geometry.html') geometry.html {% extends "base.html" %} {% block content %} {% load static %} {% load leaflet_tags %} {% leaflet_js %} {% leaflet_css %} <link rel="stylesheet" type="text/css" href="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.css' %}"> <script type="text/javascript" src="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.js' %}" ></script> <style type="text/css"> #gis {width: 100%;height:980px;} </style> <script type="text/javascript"> function our_layers(map,options){ var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{ maxZoom: 20, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }); var baseLayers = { "OSM": osm, }; L.control.groupedLayers(baseLayers).addTo(map); L.geoJSON({{ geo_json | safe }}).addTo(map); map.fitBounds(L.geoJSON({{ geo_json | safe }}).getBounds(), {maxZoom: 19}); } </script> {% leaflet_map "gis" callback="window.our_layers" %} {% endblock content %} … -
How to set `null=True` for a field using `label_from_instance`?
I am trying to set null=True and blank=True for a field using label_from_instance. But it cannot be set by defining a field in the model class. If I try to set it like the code below, I get an error. fk_id = NameChoiceField(queryset=PkModel.objects.all().order_by('pk_name').distinct(), null=True, blank=True) TypeError: init() got an unexpected keyword argument 'null' How could I set null and blank in this case? Here are the codes: forms.py from django import forms from django.forms import ModelChoiceField from .models import * class NameChoiceField(ModelChoiceField): def label_from_instance(self, obj): return f'{obj.pk_name}' class IndexForm(forms.ModelForm): fk_id = NameChoiceField(queryset=PkModel.objects.all().order_by('pk_name').distinct()) class Meta: model = FkModel fields = '__all__' models.py from django.db import models class PkModel(models.Model): pk_id = models.IntegerField(verbose_name='pk_id',primary_key=True) pk_name = models.CharField(max_length=20, verbose_name='pk_name') class Meta: verbose_name_plural = 'PkModel' class FkModel(models.Model): fk_code = models.CharField(max_length=20, verbose_name='fk_code', primary_key=True) fk_id = models.ForeignKey(PkModel, to_field='pk_id', db_column='fk_id', verbose_name='fk_id', on_delete=models.CASCADE, null=True, blank=True) class Meta: verbose_name_plural = 'FkModel' Python 3.8 Django 3.2 -
Python django model object showing None and null in template
I have this table. class MyTable(BaseModel): key = m.CharField(max_length=20,null=False,unique=True) pre_json = m.JSONField(blank=True, null=True) post_json = m.JSONField(blank=True, null=True) And I use this model through ListView/UpdateView in list html template {{obj.pre_json}} in edit html template {% render_field form.pre_json class="form-control" %} Upper one shows None in template Lower one shows null in textarea as placeholder. Why this two are shown? or can I erase these? I want to stop this -
CSV Getting decoded in wrong format in Django
I am trying to read a csv file located in AWS S3 Bucket using DefualtStorage. from django.core.files.storage import DefaultStorage def upload_file_view(request): form = CsvModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CsvModelForm() print(Csv.objects.all()[1]) obj = Csv.objects.all()[1] with storage.open("{}".format(Csv.objects.all()[1].file_name), 'rb') as f: reader = csv.reader(f.read().decode('utf-8')) for row in reader: print(row) However the row is getting printed with each word on a different line ['U'] ['s'] ['e'] ['r'] ['n'] ['a'] ['m'] ['e'] ['', ''] [' '] ['N'] ['a'] ['m'] ['e'] How am I supposed to fix this? -
Add urls to django rest swagger
I have a django rest swagger In urls.py I have something like this router = routers.DefaultRouter() router.register('', ProductListView, basename='product-list') schema_view = get_swagger_view(title="Star Shop") urlpatterns = [ path('admin/', admin.site.urls), path('api/', schema_view), path('api/', include(router.urls)) ] I'm trying to include in swagger API for products Can someone help me please -
What are the best practices to consume Kafka messages in Django
I am working on an IoT project that uses MQTT protocol to transport the sensor data from embedded devices to an App. For this i have created, A MQTT broker to send the data from the device. A custom bridge that push data from MQTT broker to my Kafka broker Django server to push the messages via websocket to the App Right now, What i need is to consume the Kafka messages from django, save to the DB and then push this data to client via websockets. But i don't have much idea regarding how to consume Kafka messages from Django. So far the solution in my mind is using custom management command, start a kafka consumer, push the data to DB and then to websockets. Is this a good approach? If not, what would be a good solution to solve this? -
HTMLButtonElement.onclick not working django
I am new to django. And I encountered an error. There are two button in a form one as submit functionality and other has onclick(to claculate values and display it in one of the input). but the onclick="fare()" not working where as static folder is linked. Please help how to call the function this is what I am getting in console Do I have to write same login in python? help me with the best way. -
How to create a queue for each of the django applications?
My project consists of three applications, amocrm, vk, tg. Everyone needs to add their turn. But I don't understand how it works. This is necessary because each of the queues in these applications will be to avoid exceeding the limit of requests to services, and some long-running tasks. If everything is sent to 1 queue, I lose a lot in performance and speed Django 4.0.2, Celery 5.2.3, RabbitMQ 3.9.13 -
How to fix Django Summernote using relative path for src url in image integration?
I am new to the Django framework, and inherited a projet which I am trying to fix. Right now my project runs in a docker at url localhost:8000 until deployment in on a remote server. I have the django-summernote extension installed for fancy text editing and image integration, but it doesn't work as expected: Summernote Editor in Django admin works fine, and correctly displays uploaded images But on my content pages, the html integration of my provides an incorrect src url (which return an error ofc) src="/media/django-summernote/2022-02-27/90a1f1ec-ed16-4cc2-a9f8-b0bb30ea4ab8.png" The expected html integration should be : src="http://localhost:8000/media/django-summernote/2022-02-27/90a1f1ec-ed16-4cc2-a9f8-b0bb30ea4ab8.png" I checked and the image file does exist in the folder, the expected url below does actually shows the picture alright as well. The rest of the website uses images integration just fine when not related to summernote. I figure this has something to do with settings.py or even router (which tbh is still a bit complex in my head). settings.py MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py urlpatterns = [ ... path("summernote/", include("django_summernote.urls")), ] -
Is there a way to put JSON data to django models?
So what I want to do here is that take a CSV file as input from an HTML form, then convert the CSV to JSON and put the JSON values into a Django model. Is there a way to do this? Any help would be appreciated. Thank you in advance! -
Default permissions for files that are automatically created in a Linux directory
I have a problem with an application developed in python using the django framework, it uses the FPDF library to export a file which is then used by the application to attach it to an automated email. When this app exports the PDF and saves it to the media directory, the file doesn't inherit permissions from its parent directory and only has read/write permissions, this doesn't allow Django to find the file so it can be attached to the mail. I was searching on the internet and found people with the same problem, they were recommended to use the ACL configuration to manage default permissions, I tried many times with different methods but it did not work. I don't know what I could have done wrong (I kept having the same error). Dfter having made the ACL configuration the files continued to be exported with the same permissions and when applying the command chmod 777 -R * these did not change their permissions, I had to disable the ACL configuration for it to allow me to apply that command. This is the error that appears: Internal Server Error: /treasury/sendMailsSupplierView/SBOJOZF Traceback (most recent call last): File "/var/www/johannasenvironment/venvjoh/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner … -
python Django returing <WSGIRequest: GET'> instead of data
I some have trouble representing API data to my templates. Some info: The API data is send to context_processors.py in my app dir. from ttn.context_processors import my_function while True: my_function(SomeClass().return_data()) time.sleep(5) and here is my context_processors funtion: def my_function(complex_data): all_data = complex_data return {'data': all_data} complex_data looks like: {0:{}, 1{}} etc.. Here is where I want to represent the data in my base.html: <div class="div-side"> {% if data %} <p>{{data}}</p> # this one return wsgirequest: get /myapp/ <ul> {% for dicts in data %} <li>dicts</li> # just for test {% for d in dicts %} <li>{{ d.name }} <span>{{d.someDigit|floatformat:'2'}}</span> <span>{{d.somePercent|floatformat:'2' }} %</span> </li> {% endfor %} </ul> {% endfor %} {%else%} <p>no info</p> {%endif%} </div> My views which render to base.html: def home_page(request): a = len(get_news_objects()) return render(request, 'base.html', {'a': a} ) Basically I'm not able to represent my data at my .html page because context_processors.py, returns this "wsgirequest: get /myapp/". What am I missing? How can I send the data instead of wsgirequest: get /myapp/ ? From my settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'project.context_processors.my_function', # ], }, }, ] -
nuxtjs auth not calling server after successful login
I'm trying to set up social logins with nuxt and django, as far as I understand it works like this: user clicks on "login with google" google returns a code nuxt calls a view on my server and sends that code the server sends the code to google which responds with the user info my server registers the user (or logs him in), generates a token and sends it back to nuxt nuxt authenticates the user I can see the google login page properly, I can click on my account, but then my local nuxt page refreshes and I don't see any request being made to my server. Is my understanding of the flow wrong? Here's my setup in nuxt: google: { clientId: '<secret_key>', codeChallengeMethod: '', responseType: 'code', redirectUri: 'http://localhost:3000/', endpoints: { token: 'social-login/google/', // some backend url to resolve your auth with google and give you the token back userInfo: 'user-info/' // the endpoint to get the user info after you received the token }, } And I'm trying to login with: this.$auth.loginWith('google') EDIT: if it helps, I'm trying to follow this guide: https://medium.com/swlh/how-to-build-google-social-login-in-django-rest-framework-and-nuxt-auth-and-refresh-its-jwt-token-752601d7a6f3 -
Is there any way to get back to a page from which it was redirected to in django?
Detailed Explanation: Suppose there is an html page in django named as Page 1 and the other one as Page 2 which is a login page. Now there is a button on both of these pages. The button on Page 1 redirects to the page for login. Is there any way to get back to that page from where this page i.e. Page 2 is redirected from? Please Note: The login page i.e. the Page 2 is simply redirected to a Account.html page, I want to set a condition so that it will redirect back to previous page, i.e., from where the Page 2 was redirected from. -
table diagnostic_patient has no column named test_id
I tried to post multiple instance in one post request.But got this error table diagnostic_patient has no column named test_id.From selected key the id will save into test_id column and name will be save in test_name column. models.py class Test(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=0) def __str__(self): return self.name class Patient(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length = 254) age = models.DecimalField(max_digits=6, decimal_places=0) gender = models.CharField(max_length=100) phone = models.DecimalField(max_digits=6, decimal_places=0) test_id = models.IntegerField() test_name = models.CharField(max_length=100) t = models.ForeignKey(Test, on_delete=models.CASCADE, related_name='selected') total_price = models.DecimalField(max_digits=6, decimal_places=0) advance = models.DecimalField(max_digits=6, decimal_places=0) due = models.DecimalField(max_digits=6, decimal_places=0) role = models.CharField(max_length=100,default='Patient') serializers.py class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields = ['id', 'name','price'] class PatientSerializer(serializers.ModelSerializer): selected = TestSerializer(many=True) class Meta: model = Patient fields = ['name', 'email', 'age', 'gender', 'phone', 'selected', 'total_price', 'advance', 'due', 'role'] def create(self, validated_data): tracks_data = validated_data.pop('selected') a = Patient.objects.create(**validated_data) for track_data in tracks_data: Patient.objects.create(**track_data) return a json post data: { "name":"df", "email":"d@gmail.com", "age":"21", "gender":"Male", "phone":"234", "total_price":86, "advance":0, "due":86, "selected":[ {"id":8,"name":"sdf","price":34}, {"id":9,"name":"dg","price":52} ] }