Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Can Auth0 JWT Tokens Be Used to Send POST Requests to Django Backend?
I was unable to find any valid documentation for the last 5-6 days on how to resolve my issue of sending POST-requests to a JWT (Auth0) secured API backend built on Django. I hope someone can help to verify if sending POST-requests is at all possible or what alternatives I may look at. My current issue stems from a supposed final major bug with using Auth0 JWT Tokens, through the Client Credential Flow M2M method. Though I may understand that I am using a very unique setup: React Frontend Django Backend No user login intended to access secured API access I guess it just now leads me to questioning on whether simply, “Can I even send POST requests to a Auth0 JWT Token secured backend?”. If it is possible, hope someone may redirect me to a potential solution, else, at least I know I really need to source something else entirely. The potential solutions I do only see with a React frontend, is to actually build a: Express.js backend Enable user-account login access This would not be ideal as both options are not the intended use case, and it will dramatically require me to change extensive code, especially to rebuild … -
pyintaller keeps giving error when converting django app to exacutable
I am trying to convert a Django project in visual studio 2019 into an executable file. I am using pyInstaller but it keeps giving me this errer: TypeError: expected str, bytes or os.PathLike object, not NoneType I have a virtual environment and a all of my necessary packages are in there the command I am using is: pyinstaller --name=mysite mysite/manage.py An error for generating an exe file using pyinstaller - typeerror: expected str, bytes or os.PathLike object, not NoneType This page explains that you need to go into one of the files of pyInstaller and replace it with a different version, but I don't know how to open the source code for pyInstaller, there is no option to do that in visual studio. 12034 INFO: Collecting Django migration scripts. 17330 INFO: Loading module hook "hook-encodings.py"... 17405 INFO: Loading module hook "hook-pkg_resources.py"... 17863 INFO: Processing pre-safe import module hook win32com Traceback (most recent call last): File "<string>", line 2, in <module> ModuleNotFoundError: No module named 'win32com' 17923 INFO: Processing pre-safe import module hook win32com Traceback (most recent call last): File "<string>", line 2, in <module> ModuleNotFoundError: No module named 'win32com' 17962 INFO: Loading module hook "hook-pydoc.py"... 17963 INFO: Loading module hook … -
General rule for djnago model class to always exclude "unpublished" instances
I'm searching a way to make some rule to exclude certain instances in each queryset. To follow DRY and to be sure that I(or some one else) will not accidentally include not accepted instances in queries. I'm relatively new in Djnago and didn't find the api to resolve this problem. class SomeClassModel(models.Model): value = models.CharField(max_length=244) accepted = models.BooleanField(default=False) How could I(or some one else) exclude not accepted instances from all queries? Even if I do SomeClassModel.objects.all() -
Django: DeferredAttribute object as string value to modify Context in class based ListView
In my template I would like to display a long name, however, I don't save the full name in the database, only a reference number. My attempted solution is to convert the Choices Tuple into a Dictionary prd_dic = dict(PRODUCTS) Then I call the Value in the dictionary with the Key name = prd_dic['0000'] In my list View, I modify the Context to feed the full name into the Template context['product_name'] = name When I pass an object into a place a string is expected a KeyError is raised (using DeferredAttribute object). My question is, is there a built in function to solve above, either in the View as a function to convert and feed into the Context, OR as making this conversion on the Model directly? The idea is to convert saved number into a full name according a key table to be displayed in Template. Thankful for some input. PRODUCTS = ( ('0000' , 'Hamburger'), ('1111' , 'Pizza') ) class Product(models.Model): product_number = models.CharField(max_length=20,choices=PRODUCTS, blank=True, null=True) class ProductListView(ListView): model = Product template_name = 'product/product_list.html' def get_context_data(self, **kwargs): context = super(ProductListView, self).get_context_data(**kwargs) prd_obj = Product.product_number # this is an object prd_dic = dict(PRODUCTS) name = prd_dic[prd_obj] # a single … -
how i can show my WYSIWYG Editor in my template django (html)
i want ues my data of WYSIWYG Editor in my model and show in my template django(html). my FroalaField in my model is : description = FroalaField(theme="dark",blank= True, null= True, verbose_name = 'message', help_text = 'Write Full Text') i use |safe in my template but it isn.t work! -
Django strange behaviour when an exception occurs, using django-rest-framework
I'm developing some REST api for a webservice. Starting from some days I've experienced a big problem that is blocking me. When the code has an exception (during developing) the django server respond only after 5/8 or 10 minutes... with the error that occurs. To understand what is happening I've started the server in debug using pycharm.... and then clicking on pause during the big waiting.. the code is looping here into python2.7/SocketServer.py def _eintr_retry(func, *args): """restart a system call interrupted by EINTR""" while True: try: return func(*args) except (OSError, select.error) as e: if e.args[0] != errno.EINTR: raise print(foo) What can I do? I'm pretty desperate! -
nonetype' object has no attribute 'decode' error when i upload the image to database
i am new to ionic4/angular4.i need to upload the profile pic to database.i wrote code but i don't know whether it is correct or not and when i am uploading it i am getting the above mentioned error. backed i am using Django and sorry for the bad indentation.i just beginner to programming. .ts async sendPictureToSomewhere() { const fileuri = await this.getPicture(); const blobinfo = await this.b64toBlob(fileuri); await this.upload(blobinfo); alert("done"); } async getPicture() { const options: CameraOptions = { quality: 100, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE // targetWidth: 200 }; let fileuri = await this.camera.getPicture(options); return fileuri; } b64toBlob(_imagePath) { return new Promise((resolve, reject) => { let fileName = ""; this.file .resolveLocalFilesystemUrl(_imagePath) .then(fileEntry => { let { name, nativeURL } = fileEntry; // get the path.. let path = nativeURL.substring(0, nativeURL.lastIndexOf("/")); console.log("path", path); console.log("fileName", name); fileName = name; // we are provided the name, so now read the file into // a buffer return this.file.readAsArrayBuffer(path, name); }) .then(buffer => { // get the buffer and make a blob to be saved let imgBlob = new Blob([buffer], { type: "image/jpeg" }); console.log(imgBlob.type, imgBlob.size); resolve({ fileName, imgBlob }); }) .catch(e => reject(e)); }); } upload(_Blobinfo) { this.profileService.postInfluencerProfile(_Blobinfo, null, null).subscribe( response => … -
Customize Django TabularInline intermediate model
Let's say I have two records in the Person table: John and Matthew. In the admin Group form, for every Group I would like to be able to add one person (from existing ones - IMPORTANT) and specify a membership. I want the combination of membership_id, person and group to be unique within the Membership table. I have tried TabularInline and it looks very promising, but I found some troubles with the solution. Imagine I have clicked GOLD for Membership, John for Person and then Add another Membership. Since John has already been used, he should not be visible as an option, but he is. I mean field combination constraint is not followed in the form. How can I change that? Models: class MembershipEnum(Enum): gold = 'GOLD' silver = 'SILVER' @classmethod def choices(cls): """Return Django-style choices for the model.""" return tuple((s.name.upper(), s.value) for s in cls) class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) name = models.CharField(max_length=300, choices=MembershipEnum.choices(), blank=False, default=None) class Meta: unique_together = [["id", "person", "group"]] Admin module: class MembershipInline(TabularInline): model = Membership extra = 1 class GroupForm(ModelForm): """Display Domain objects in the … -
AppConfig override restricts first makemigration
I am overriding the AppConfig and adding below in __init__ default_app_config = 'api.apps.AppnameConfig' which has some models check I want to create them if doesnot exits all works fine. But when I am deploying this to another machine python manage.py makemigrations fails obviously because there are no tables created as there is no migration on fresh project. It is raising ProgrammingError I can do try pass on this but I dont want to go this way. I also checked if migrations folder exists works fine but again fails on migrate. Please suggest best way to do this. -
Django Readiness Probe Fails
I am implementing RollingUpdate and Readiness/Liveness Probes into a Django deployment. I created an /healthz endpoint which simply returns OK and 200 as response code. The endpoint is manually working as expected. However when kubernetes is trying to reach that endpoint, it times out. Readiness probe failed: Get http://10.40.2.14:8080/v1/healthz/: net/http: request canceled (Client.Timeout exceeded while awaiting headers) But from the Django access log I can clearly see that it is indeed querying this endpoint periodicaly and it is retuning bytes of data and 200 as response. [api-prod-64bdff8d4-lcbtf api-prod] [pid: 14|app: 0|req: 34/86] 10.40.2.1 () {30 vars in 368 bytes} [Wed Jul 3 12:10:18 2019] GET /v1/healthz/ => generated 15 bytes in 3 msecs (HTTP/1.1 200) 5 headers in 149 bytes (1 switches on core 0) [api-prod-64bdff8d4-lcbtf api-prod] [pid: 13|app: 0|req: 11/87] 10.40.2.1 () {30 vars in 368 bytes} [Wed Jul 3 12:10:52 2019] GET /v1/healthz/ => generated 15 bytes in 2 msecs (HTTP/1.1 200) 5 headers in 149 bytes (1 switches on core 0) This is my yaml file readinessProbe: httpGet: path: /v1/healthz/ port: 8080 initialDelaySeconds: 30 periodSeconds: 60 successThreshold: 1 livenessProbe: httpGet: path: /v1/healthz/ port: 8080 initialDelaySeconds: 30 periodSeconds: 60 successThreshold: 1 Where did the request goes?