Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ejabberd Django External Authentication not working
I'm working on a Django Website which needs a Chat System, therefore I wanted to implement an XMPP Server which authenticates against the Django Backend. I've been using different Ejabberd External Authentication scripts like django-xmpp, django-ejabberd-bridge and one which can be found at https://www.ejabberd.im/files/contributions/ejabberd_auth_bridge.py.txt But yet none of them has worked. The script provided by django-xmpp crashes during login to the XMPP Server with the error An error has occurred during eJabberd external authentication: unpack requires a buffer of 2 bytes Traceback (most recent call last): File "/home/dcpacky/Public/plutus.live/userdashboard/management/commands/ejabberd_auth.py", line 105, in handle data = self.from_ejabberd() File "/home/dcpacky/Public/plutus.live/userdashboard/management/commands/ejabberd_auth.py", line 40, in from_ejabberd (size,) = struct.unpack(">h", input_length) struct.error: unpack requires a buffer of 2 bytes And then the authentication script crashes. The same error occures using django-ejabberd-bridge but since django-xmpp is based of django-ejabberd-bridge, it's probably the same error origin. When I've been using the implementation found in the Ejabberd documentation, which is linked above, the following error occurs. Traceback (most recent call last): File "/home/dcpacky/Public/plutus.live/userdashboard/management/commands/ejabberd_auth.py", line 126, in handle size = struct.unpack('>h', length)[0] TypeError: a bytes-like object is required, not 'str' I tried around using functions like str(), encode(), decode() and so on but yet wasn't able to get it working. … -
Pass variable from view to form in Django
I am building a simple task management system, where a Company can have multiple projects, and each company has employees. I want a form that allows managers to add users to projects, with the constraint that the available users belong to the company. I am passing the variable company_pk from the view to the form, but I am not sure how to set/access the variable outside the init finction. class AddUserForm(forms.Form): def __init__(self, company_pk=None, *args, **kwargs): """ Intantiation service. This method extends the default instantiation service. """ super(AddUserForm, self).__init__(*args, **kwargs) if company_pk: print("company_pk: ", company_pk) self._company_pk = company_pk user = forms.ModelChoiceField( queryset=User.objects.filter(company__pk=self._company_pk)) form = AddUserForm(company_pk=project_id) As mentioned, I want to filter the users to only those belonging to a given company, however I do not know how to access the company_pk outside of init. I get the error: NameError: name 'self' is not defined -
Trying to have display a csv file without downloading Django Rest Framework
I'm trying to display a csv file like I would normally do with Json or XML with Django Rest. Here's an example of what I have. For some reason when I press the 'csv' button it automatically downloads it. I want to view it in separate page like I normally do with the 'Json' and 'xml' option. I am using the djangorestframework-csv package. This is what I have in my settings for the project. REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_xml.renderers.XMLRenderer', 'rest_framework_csv.renderers.CSVRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework_xml.parsers.XMLParser', 'rest_framework_csv.parsers.CSVParser', ) -
How to implement two QuerySets in .HTML (Noob-Question)
I'm new to Django and trying to understand how it works. Basically I'm building this simple Blog and I have one Question regarding the implementation of the QuerySets in my .HTML file. This is how my code looks like: Models.py class Post(models.Model): [...] class Highlight(models.Model): [...] Views.py from django.shortcuts import render from django.utils import timezone from .models import Post from .models import Highlight def post_list(request): posts = Post.objects.all return render(request, 'blog/post_list.html', {'posts': posts}) def highlight_list(request): highlights = Highlight.objects.all return render(request, 'blog/post_list.html', {'highlights': highlights}) Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name='post_list'), path('', views.highlight_list, name='highlight_list'), ] post_list.html {% for post in posts %} {{ post }} {% endfor %} {% for highlight in highlights %} {{ highlight }} {% endfor %} The problem is, it only shows the objects from the class Post. Is it somehow possible to include both QuerySets from both classes? If yes, what am I doing wrong? :x Thank you! -
How to execute view differently if it is coming from a different URL?
So I want to make a message app in Django. There is a view that used for deleting message. It just hides the message if user clicks delete. It changes the boolean field of message 'hide' to True if executed. I have two different template, Inbox and Outbox. I want to have delete feature for booth of these. But want to use the same view. I just want to check if the request is comming from Outbox, then I will change to_hide. If the request is comming from Inbox I will change frm_hide. But I don't know how to catch the URL in view and condition them to perform different function. Message Model class Msgs(models.Model): to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') frm = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user') title = models.CharField(max_length = 255) body = models.CharField(max_length=2000) date = models.DateTimeField(auto_now=True) to_hide = models.BooleanField(default=False) frm_hide = models.BooleanField(default=False) def __str__(self): return f'{self.frm} to {self.to}: {self.title}' ## Delete/Hide View @login_required def deletemsg(request, msg_id): msg = Msgs.objects.get(pk=msg_id) msg.frm_hide = True msg.save() return redirect('/msgs/inbox/') # inbox url: http://127.0.0.1:8000/msgs/inbox/ # outbox url: http://127.0.0.1:8000/msgs/outbox/ -
Django channels can't log exceptions in console
Django-Channels can't show exception error in console When an exception raise in any section of my consumer. it just show "WebSocket DISCONNECT /ws/test/ [127.0.0.1:7907]" in console when exception occurred. I run project with debug=True setting with this command: python3 manage.py runserver I use base settings for django-channles: # CHANNELS # ------------------------------------------------------------------------------ ASGI_APPLICATION = "config.routing.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } and have a very simple consumer: class Test(WebsocketConsumer): def connect(self): print(self.scope['headers']) self.accept() def receive(self, text_data=None, bytes_data=None): print(text_data) -
django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'handshake: reading inital communication packet', system error: 0")
I am developing an app in django to push it on Heroku, and while trying to migrate a database in mysql to heroku, I pip installed mysql..something and as I try to run the server, I got this error: django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'handshake: reading inital communication packet', system error: 0") (I had my virtual environment on). The strange thing is that the package installed python even if I had that already installed. I found out that it unistalled django and several modules I previously installed. I re-installed the modules but now as I run the server I get that error above. If I run the server from another app directory, the database runs fine. Is it maybe related to something I had installed in my directory and maybe was apparently overwritten by the strange package? here is my pip freeze result: certifi==2019.6.16<br> dj-database-url==0.5.0<br> Django==2.2.3<br> django-heroku==0.3.1<br> gunicorn==19.9.0<br> mysql-connector-python==8.0.16<br> mysqlclient==1.4.2.post1<br> protobuf==3.6.0<br> psycopg2==2.8.3<br> PyMySQL==0.9.3<br> python-decouple==3.1<br> pytz==2019.1<br> six==1.12.0<br> sqlparse==0.3.0<br> whitenoise==4.1.2<br> wincertstore==0.2<br> -
Font-Awesome CSS file not working but Font-Awesome CDN works. Why?
I am building my own website and am hosting my static files in an AWS S3 bucket. Everything on my site seems to work except for the CSS file that contains all of the font-awesome CSS information. In this case, my social media icons and all of the other icons that font-awesome has to offer wouldn't work even though I triple checked that the path was correct (Checked in aws as well as through inspection on chrome. The paths matched) I recently added the font-awesome CDN and now they all appear. While I am happy that I resolved the issue, I would really like to know why the CSS didn't work. I downloaded the CSS file from bootstrapmade so everything should work just like they created it. Could anyone tell me why this might be the case? I have run into this a few times and am wondering if there is something that I am missing. I am currently using Django 2.3 with Python 3.7.3. <!-- Libraries CSS Files --> <link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' rel='stylesheet' type='text/css'> <link href="{% static 'static/lib/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet"> <link href="{% static 'static/lib/owlcarousel/owl.carousel.min.css' %}" rel="stylesheet"> <link href="{% static 'static/lib/owlcarousel/owl.theme.min.css' %}" rel="stylesheet"> <link href="{% static 'static/lib/owlcarousel/owl.transitions.min.css' %}" rel="stylesheet"> -
How to migrate to dockerfile if the database is in another container?
Such situation: There is a container with a dB and Django container of the application which through-link connects to a dB and starts itself: FROM deb_base COPY vfnd vfnd CMD ["python", "./vfnd/manage.py", "runserver", "0.0.0.0:8001"] The bad thing is that you have to run python vfnd/manage.py migrate manually every time I launch the containers. Tried the following code: FROM deb_base COPY vfnd vfnd RUN ["python", "./vfnd/manage.py", "migrate"] CMD ["python", "./vfnd/manage.py", "runserver", "0.0.0.0:8001"] However, when you try to build the image, you receive an error on this command Step 3/4 : RUN ["python","./vfnd/manage.py","migrate"] ---> Running in 5791de6fc147 Traceback (most recent call last): File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/django/db/backends/b ase/base.py", line 216, in ensure_connection self.connect() File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/django/db/backends/b ase/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/django/db/backends/p ostgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/psycopg2/__init__.py ", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "pg_1" to address: Name or service not known How can I implement my idea -
How to post data in textarea inside table in Django?
I have multiple text area inside side a table which has the same id. How can I post textarea value in views? Note:-i want to post textarea data with template table row id but I don't know how. -
Django memcached does not cache view when redirecting from same view
I currently have memcached installed on my Django server. I have two views: index and results. From the index I use a post form method to redirect me to the results view based on the search. The memcached works fine here. The results view gets cached correctly. However this only works from the index view. In the results view I give the user the option to search again which redirects the user back to the results view on same input, but this view is not cached. I used a time.sleep() timer to see if the page was being cached. I've tried messing around with urls.py as I currently have a regular expression for the url match, but no luck here. I'm not exactly sure where the error could be persisting from. @cache_page(61*1) def index(request): if request.method == 'POST': return redirect(results, input_1=some_input) @cache_page(61*1) def results(request, input_1): time.sleep(2) # Using this to test view cache if request.method == 'POST': return redirect(results, input_1=some_input) The code above is stripped down, but it gets the idea of what I'm trying to do across. Thank you for your help. -
How to get image name in django without extension name
How can i get image name without extension name I'm using this code but output= imagename.jpg . {{ post.image.name }} I want like this output=imagename -
django, pass mutliple files to api, including other parameters
I am new to Django. I am building a Django REST API to call NLP models. So the way i am seeing it is that I would have 100 xml files and some 6 different models that I would be running on them. So I would have to send the 100 xml files in byte array form, including the information about these 6 models that I want to run, through API. My question is what is the best approach I should take Is it ok to convert all xml to byte [] and pass them to API in json format along with model information in one API call? I am worried that might be a lot to send our the one api call. The xml files are of size 100 to 200k Should I copy the files to the server aside of calling REST API and once copied, I pass on the model informaton thrugh API. -
Django - get auto_now field in pre_save signal
I'm using Django 2.1.5. There is a model with 'auto_now' field: class BaseModel(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True) updated_at = models.DateTimeField(db_index=True, auto_now=True) updated_by = models.CharField(max_length=200) responded_at = models.DateTimeField(db_index=True, null=True, blank=True) responded_by = models.CharField(max_length=200, null=True, blank=True) Now, I have a pre_save signal for that model, and I want to update there the responded_at and responded_by fields to be equal to updated_at and updated_by. In that signal - the updated_by value is already the new one, as supposed to be in the end of the request, but the updated_at is not. It's the old (current) value. I want, if possible, to be able to get the value that supposed to be in updated_at field after the save. The reason I'm using pre_save signal and not post_save is because I'm updating the instance inside it. -
Is there any way to set the font color to models.CharField for a snippet in Wagtail?
I'd like to set the font color as the user wishes. For example, typing "I'd like to set to RED." in the charfield, I wanna make only "RED" the red color. I was looking at to use richtext somehow, but seems impossible. What should I do? -
Cannot login user for testing with selenium in Django?
I've got the following test: class FirefoxTestCases(StaticLiveServerTestCase): def setUp(self): user = User.objects.create( first_name="user", last_name="one", username="userone", is_active=True, ) user.set_password("test") user.save() self.client = webdriver.Firefox() def tearDown(self): self.client.quit() def test_log_in_displays_firefox(self): # Opening the link we want to test self.client.get(self.live_server_url) assert "log in" in self.client.page_source self.client.find_element_by_id("id_username").send_keys("userone") self.client.find_element_by_id("id_password").send_keys("test") self.client.find_element_by_id("log_in").click() time.sleep(2) # Check the returned result assert "appone" in self.client.page_source The app takes you to a login page right off the bat and talks to a log_in view def log_in(request): if request.user.is_authenticated: return redirect("launcher") if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): user = authenticate( request, username=request.POST.get("username"), password=request.POST.get("password"), ) if user is not None: login(request, user) # 500 error occurs here return redirect("launcher") return render(request, "launcher/login.html", {"form": form}) else: form = LoginForm() return render(request, "launcher/login.html", {"form": form}) The form submits without issue but it gives a 500 error in the logs. It redirects to the login page again (expected). I have another test where I login the same user programmatically that does work: class TestViews(TestCase): def setUp(self): user = User.objects.create( first_name="user", last_name="two", username="usertwo", is_active=True, ) user.set_password("test") user.save() def test_logged_in_one_app_returns_200_and_launcher(self): """ A user with one app sees the launcher.html page """ user = User.objects.get(username="usertwo") user.set_password("test") user.save() test_client = Client() test_client.login(username="usertwo", password="test") response = test_client.get("/", follow=True) self.assertEqual(response.status_code, … -
Why in the template one phrase was translated, and the second one was not?
I do not understand, why in the template one phrase was translated, and the second one was not? python mana.py makemessages python manage.py compilemessages settings LANGUAGE_CODE = 'ru' USE_I18N = True LANGUAGES = ( ('ru', gettext('Russian')), ('kk', gettext('Kazakh')), ) MODELTRANSLATION_DEFAULT_LANGUAGE = 'ru' TEMPLATES = [ { 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.i18n', 'solid_i18n.middleware.SolidLocaleMiddleware', SOLID_I18N_USE_REDIRECTS = True template {% load l10n i18n %} <div>{% trans credit.creditpayment_set.first.security %}</div> #It's translated <div>{% trans credit.creditpayment_set.first.comission_type %}</div> #It's not translated django.po (ru) security #: credits/models.py:70 msgid "Pledge - real estate" msgstr "залог - имеющееся недвижимость" comission_type #: credits/models.py:156 msgid "For consideration" msgstr "Комиссия за рассмотрения" -
I am getting an error on Gunicorn after pressing on my server "sudo systemctl status gunicorn"
getting an error, after pressing: sudo systemctl status gunicorn gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2019-07-03 11:20:47 UTC; 2h 56min ago Process: 9754 ExecStart=/usr/local/bin/gunicorn --workers 3 --bind unix:/home/root/portfolio-project/portfolio.sock portfolio.wsgi:application (code=exited, status=21 Main PID: 9754 (code=exited, status=216/GROUP) Jul 03 11:20:47 django2-protfolio systemd[1]: Started gunicorn daemon. Jul 03 11:20:47 django2-protfolio systemd[9754]: gunicorn.service: Failed to determine group credentials: No such process Jul 03 11:20:47 django2-protfolio systemd[9754]: gunicorn.service: Failed at step GROUP spawning /usr/local/bin/gunicorn: No such process Jul 03 11:20:47 django2-protfolio systemd[1]: gunicorn.service: Main process exited, code=exited, status=216/GROUP Jul 03 11:20:47 django2-protfolio systemd[1]: gunicorn.service: Failed with result 'exit-code'. lines 1-14/14 (END) -
Ho to capture complicated database transactions over multiple forms in Django
I need to capture some fairly complicated database changes from my users, including both updating and creating objects for multiple models. I feel like the obvious way to do this would be by leveraging a sizeable amount of Javascript to create a JSON object containing all the necessary changes that can be POSTed in a single form. I am not keen on this approach as it prevents me from utilizing Django's CreateView and UpdateView classes, as well as the validation that comes with them. Also I am more comfortable in Python than Javascript. I want to use a series of form POSTs to build up the necessary changes over time, but also need the transaction to be atomic, which, as far as I know, is not possible in Django. Another complication is that the models contain non-nullable fields and I would need to create objects before capturing the user input required to fill them. I do not want to make these fields nullable or use placeholders as this would make it more difficult to validate. One approach I am considering is to create a duplicate of each of the necessary models to store partial objects. All fields would be nullable … -
how to handle a media file without save it in django
In my django project, I received a media file posted from client. like this def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file'], request.POST['fid']) return JsonResponse({"result":"ok"}) return JsonResponse({"result":"failed","msg":"unkown"}) def handle_uploaded_file(f, fid): with open(STEP_DIR + '/' + fid, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) On the other hand, I want to process this file by another module. And this module will open a file and handle it like this: Import thirdModule thirdModule.open('path_to_url').exporter(...) As the thirdModule will open a file by a given path. So I have to save the file which I had just received from django ? Is there any way I can process the file directly with out save it.like is: def handle_uploaded_file(f, fid): thirdModule.open(convert_media_to_stream(f)) ... -
How to change boolean field "isActual" by date
I'm new in Django Rest Framework. I have this model - class Post(models.Model): created = models.DateTimeField(auto_now_add=True) description = models.CharField(verbose_name='description', db_index=True, max_length=64) In this model, I want to add field "isActual", which value equal True or False. His value must be False, if Post created more than 1 month (check field "created"). I don't know how to create it. Is it possible? -
How can I incorporate a foreign key into a django form?
Is there a way that a foreign key can be incorporated into Django forms, or widgets into Django models? I'm using Django 2.2.2 and I have a model created (Accelerator). I have also created a form (Review). I have created Review using Django forms because I need to use widgets to ensure certain fields display as radio buttons, and I understand that widgets can't be used in models. However, I also need one of my Review form fields to be a foreign key linking to the Accelerator model, but my terminal has just informed me that this is an attribute that Django forms doesn't have. How can I create a model or form which can make use of both widgets and foreign keys? Ultimately, I need for my Accelerators model to inherit a value from my Review form, probably by way of another foreign key. class Accelerator(models.Model): name = models.CharField(max_length=100) summary = models.TextField() overall_rating = models.DecimalField(decimal_places=2, max_digits=3) author = models.ForeignKey(User, on_delete=models.CASCADE, default='admin') logo = models.ImageField(default='default.jpg', upload_to='logos') def __str__(self): return self.name RATINGS = ['1', '2', '3', '4', '5'] class Review(forms.Form): subject = forms.ForeignKey(Accelerator, on_delete=models.CASCADE, blank=False) author = forms.ForeignKey(User, on_delete=models.CASCADE, blank=False) feedback = forms.TextField(blank=False) date_posted = forms.DateTimeField(default=timezone.now) mentorship = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS)) hiring = … -
Django QuerySet filter get last object before a date_time cut off
I'm trying to keep a QuerySet lazy (unevaluated) while building it and the goal i have is to find the last event prior to a give date. class Event(models.Model): date_time = models.DateTimeField('Date and time of event') class Meta: ordering = ['-date_time'] Now I have a cut_off date_time and I can get all the Events after this cutoff easily with: events = Event.objects.filter(date_time__gte=cut_off) Now I'd like to include the last Event prior to cut_off as well! I can think of a number of ways to do this that cause database hits but I'd like to find a solution that keeps the QuerySet lazy. A clear candidate is the window Lag function. If we annotate the events with the date_time of the next Event, something like this conceptually works: window_lag = Window(expression=Lag("date_time"), order_by=F("date_time").desc()) annotated_events = Event.objects.annotate(date_time_next=window_lag) events = annotated_events.filter(date_time_next__gte=cut_off) But alas that's not legal (yet): https://code.djangoproject.com/ticket/28333 It can be done (and I have done it) by using raw SQL but again, ouch. I would like to keep this as clean as I can and the QuerySet lazy (no database hits in building it). Is there any create way to write filters that do not use window functions, can remain lazy yet achieve … -
How to make a copy of related field in django-rest-framework
fields is a list of EavAttribute name likes ['a', 'b', 'c'] fields_order is a list of EavAttribute order likes [1,2,3] I want to make a copy of fields to serializer a order field list. class EavForm(models.Model): name = models.CharField(max_length=300) class EavAttribute(models.Model): form = models.ForeignKey(EavForm, on_delete=models.CASCADE, related_name='fields') name = models.CharField(max_length=300) order = models.IntegerField(default=1) class EavFormSerializer(serializers.ModelSerializer): fields = serializers.SlugRelatedField(many=True,read_only=True,slug_field='name') # not work here ,how to fix fields_order = serializers.SlugRelatedField(many=True,read_only=True,slug_field='order') class Meta: model = EavForm fields = '__all__' -
Cannot access array passed by post
I'm processing a form passing (by post) the data to a view. From the view if i print the whole request.POST object I get: <QueryDict: {'csrfmiddlewaretoken': ['<omitted>'], 'doctype-name': ['a7'], 'doctype-validita': ['1'], 'projects': ['1', '2']}> If i try to read or print request.POST['projects'] I get only the last value i.e. 2