Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn service fails to start
Gunicorn not starting Hi, I expect this is not the right subreddit for this unfortunately, but becuse it is a django application I've come here as a starting point. But for some reason, gunicorn service will not start on one of my servers. The gunicorn.service and the gunicorn.socket files are identical and in identical locations (I am building a staging server so it must be as close to the other one as possible, the other one is running fine). Can anyone see what might be the issue gunicorn.service: #!/bin/sh [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=pcc Group=nginx WorkingDirectory=/home/rob/myproject ExecStart=/home/rob/anaconda3/envs/django_env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application [Install] WantedBy=multi-user.target gunicorn status: (django_env) [rob@pcc-home-page run]$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Wed 2020-03-11 12:45:25 UTC; 13s ago Process: 1466 ExecStart=/home/rob/anaconda3/envs/django_env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application (code=exited, status=203/EXEC) Main PID: 1466 (code=exited, status=203/EXEC) Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: Started gunicorn daemon. Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: gunicorn.service: main process exited, code=exited, status=203/EXEC Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: Unit gunicorn.service entered failed state. Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: gunicorn.service failed. Some extra info: Server is running CentOS, Django is purely running … -
Django - check if two password hashes are of same raw password
I want to keep track of user password change history, and display a warning if their current password is used by them before. To note, I don't want to prevent a user from setting a password if it is used before, I want to let them set the password, but just display a warning afterwards. So what I'm looking for is NOT a password validator. I know that while Django saves user passwords in the db, it creates a hash of the password, using a random salt. So 2 hashes of the same password will not be the same. Still, is it possible to tell if 2 different password hashes are created with the same raw password as the input? -
Django template - iterate a list of tuples, each tuple is a string, dictionary
I have a dictionary that has been turned into a sorted list, which creates the below: monthly_spend_provider = sorted(monthly_spend_provider.items(), key=lambda item: item[1]['cost'], reverse=True) monthly_spend_provider [ ('PROVIDER A', {'cost': Decimal('10000'), 'symbol': '£'}), ('PROVIDER B', {'cost': Decimal('9000'), 'symbol': '$'}), ('PROVIDER C', {'cost': Decimal('8000'), 'symbol': '$'}), ('PROVIDER D', {'cost': Decimal('7000'), 'symbol': '£'}), ] now im trying to access the data in the tuples in a Django template thus far unsucessfully. I thought the below would of worked but it hasn't {% for provider in monthly_provider_country %} {% for data in provider %} <h3>{{ provider }} {{ data.symbol }} {{ data.cost|currency }}</h3> {% endfor %} {% endfor %} can I do this in a template or is there a way to turn the sorted list back into an easier format to output into a template? Thanks -
How to add model form field in the constructor?
I am trying to add a field in a ModelForm but only if a certain condition is met, which is passed through the constructor, so I can't just do: class MyForm(models.ModelForm): class Meta: model = MyModel fields = ['myfield'] I know I can manually add it like this: class MyForm(models.ModelForm): def __init__(self, condition, *args, **kwargs): if condition: self.fields['myfield'] = forms.CharField() But that would be missing attributes from the model definition (max_length, help_text, validators...), not to mention the actual initial and data values if the instance exists. PS: yes I'm on Django 1.8, don't ask why. -
Django Model validation based on a field value of another Model
I have this Django model: from accounts.models import Account class BankOperation(models.Model): created_at = models.DateTimeField(auto_now_add=True) account = models.ForeignKey(Account, on_delete=models.CASCADE) operation_import = models.FloatField(default=0.0) I want to make sure that the operation_import is not higher than account.balance what is the official way to this? I have seen some answers talking about overriding the save() method but others advise against it. should i add a pre-save signal and throw some kind of exception? Is there a way to create a field validator that accepts parameters? so maybe something like: def validate_bank_operation_import(value, account_balance): if value > account_balance: raise ValidationError("Bank operation import is higher than account balance!") and inside my model i change the field to: operation_import = models.FloatField(default=0.0, validators=[validate_bank_operation_import]) But can i pass parameters to a validator? if yes, how do I do it? perhaps there is another to do this validation! -
Setting the field value of a form in view.py
My django website would like to allow logged in users to post a recipe. The recipe model is linked to the user model and as such requires a valid user instance. I would like the Recipe form to automatically assign the postedby field to the instance of the logged in user. So far I have attempted to pass in a dictionary, storing the user's name, to the form instance. as shown in the view However, the constructor method is not receiving the data and is rendering the form but with a failed attempt to submit. I cannot store the data without postedby field having a valid instance as the model throws the following error: Exception Value:UserProfile matching query does not exist. I have also tried to do the following in views.py; @login_required def add_recipe(request): form = RecipeForm() form.fields['postedby'] = UserProfile.objects.get(user=User.objects.get(username=request.user.__str__())) context_dict = {'form':form} if request.method == 'POST': ... However this overwrites the postedby form view to be rendered and raises and error. views.py @login_required def add_recipe(request): form = RecipeForm({'user':request.user}) context_dict = {} #print(form.fields['postedby'].queryset) if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect(reverse('spatula:index')) else: print(form.errors) context_dict['form'] = form return render(request, 'spatula/add_recipe.html', context=context_dict) The RecipeForm is as follows: class … -
ModelChoiceField always raises : “Select a valid choice. That choice is not one of the available choices”
In forms I have multiple dependent choice fields. but I am getting same error for all the dependent choice fields i tried but it wont come please help me.I am fresher. forms.py class IssuecreateForm(forms.ModelForm): def __init__(self,*args, **kwargs,): self.projects = kwargs.pop("projects",None) # self.issues = kwargs.pop("issues",None) # self.rootcause = kwargs.pop("rootcause",None) super(IssuecreateForm, self).__init__(*args, **kwargs) self.fields['SUMMARY'].widget.attrs.update({'class' : 'form-control','placeholder': 'Enter Summary'}) self.fields['SUMMARY'].label='Summary' self.fields['DESCRIPTION'].widget.attrs.update({'class' : 'form-control mb-4','placeholder': 'Enter Description'},required=False) self.fields['DESCRIPTION'].label='Description' self.fields['ENVIRONMENT'].widget.attrs.update({'class' : 'form-control mb-4','placeholder': 'Enter Description'},required=False) self.fields['ENVIRONMENT'].label='Environment' self.fields['PROJECT'].queryset = self.projects self.fields['LINKED_ISSUES'].choices = [(x.ID, x.SUMMARY) for x in Issues.objects.all()] LABELS =forms.MultipleChoiceField(widget=forms.Select({'class': 'lable-select', 'name':"lable-select", "multiple":"multiple"}), choices=OPTIONS,required=False) CREATED_DATE_TIME=forms.DateTimeField(initial=datetime.datetime.today(),required=False) PROJECT = MyModelChoiceField(queryset=Project.objects.all(),widget=CustomSelectOption(attrs={'class':'mt-2'})) PRIORITY = MyModelChoiceField(queryset=Priority.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2','name':'issue-types'})) TYPE = MyModelChoiceField(queryset=IssueType.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2'})) LINKED_ISSUE_TYPES = ModelChoiceField(queryset=LinkedIssueType.objects.none(), empty_label='----------Select Linked Issue Type---------') # STATUS = ModelChoiceField(queryset=IssueStatus.objects.none(), empty_label='----------Select Status---------') RESOLUTIONS = ModelChoiceField(queryset=Resolution.objects.none(),required=False, empty_label='----------Select Resolution---------') ROOT_CAUSES = ModelChoiceField(queryset=RootCause.objects.none(),required=False, empty_label='----------Select Rootcause---------') PROCESS_AREAS = ModelChoiceField(queryset=ProcessArea.objects.none(),required=False, empty_label='----------Select Process Area---------') FUNCTIONAL_AREAS = ModelChoiceField(queryset=FunctionalArea.objects.none(),required=False, empty_label='----------Select Functional Area---------') # DEFECT_TYPE = ModelChoiceField(queryset=DefectType.objects.none(), empty_label='----------Select Defect Type---------') ASSIGNEE = MyModelChoiceField(queryset= PmUser.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2'}),required=False) REPORTER = MyModelChoiceField(queryset= PmUser.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2'}),required=False) SPRINTS = ModelChoiceField(queryset=Sprint.objects.none(),required=False, empty_label='----------Select Sprint---------') LINKED_ISSUES = forms.MultipleChoiceField(widget=forms.Select({"class":"issue-list", "name":"issue-list", "multiple":"multiple"}),choices = [],required=False) # EPIC_LINK = forms.MultipleChoiceField(widget=forms.Select({"class":"issue-list", "name":"issue-list"}),choices = []) DURATION_CHOICES=forms.ChoiceField(widget=forms.RadioSelect(attrs={'placeholder': 'METHOD_TYPE','class':'myclass'}),required=False,choices=DURATION_CHOICES) class Meta: model = Issues fields ='__all__' exclude=['CREATOR','UPDATOR','CREATED_DATE_TIME','UPDATED_DATE_TIME','EPIC_LINK','WATCHER','PARENT','LINKED_ISSUES','ORDER','SERIAL_NUMBER','COLOR','DEFECT_TYPE','STATUS','EPIC_NAME'] widgets = { 'START_DATE': DateInput(), 'DUE_DATE': DateInput(), 'ESTIMATION_TIME': DurationInput(), } -
Django models foreignkey default value
There was no manager in the posts I created before. When I add the manager, I want the default value or I am asked to enter it manually. When I enter 'None' I get an error like this; django.db.utils.IntegrityError: NOT NULL constraint failed: new__Core_post.manager_id I cannot export PostManager as the default value. Is there another way or another solution to give? class User(models.Model): #... posts = models.ManyToManyField('Post', blank=True) class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) #... manager = models.ForeignKey('PostManager', on_delete=models.CASCADE) class PostManager(models.Model): #... Sorry for my bad english. -
Obtain all the columns from my model in django
I want to obtain all the info from one table of my database in django, I'm doing this, from django.shortcuts import render # Create your views here. from Platform_App.models import fleets def list_fleets(request): fleet = fleets.objects.all() return render(request, template_name='fleets.html', context={'Fleet':fleet}) But it shows an error in the line below, concretely in fleets. fleet = fleets.objects.all() It says, class fleets has no objects member My model is the following: class fleets(models.Model): fleet_id = models.IntegerField(primary_key=True) fleet_name = models.CharField(max_length=20) description = models.CharField(max_length=40, blank=True, null=True) If fleet = fleets.objects.all() is not correct, how I have to do it to take all the columns of my table?? Probably a easy question, but I'm newbie. Thank you very much!!!! -
Can't connect to website with LetsEncrypt certificate - nginx
I'd like to add ssl certificate to my django app. I've followed tutorial so the nginx config for domain was changed but now it looks like generated certificate is incorrect. nginx conf before certbot modifications server { listen 80; listen [::]:80; server_name doamin.com www.domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/poul3r/doamin.com; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and after certbot action server { server_name doamin.com www.doamin.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/poul3r/doamin.com; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/doamin.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/doamin.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = doamin.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name doamin.com www.doamin.com; return 404; # managed by Certbot } What I'm doing wrong or what could went wrong during letsencypt implementation ? -
Importing a JS file on Django
I created a simple file called main.js. In this file, i defined a function: function hello(){ console.log('hello') } Now i'm trying to import the file on a template and call the function from there. Here is what i tried: <script type="text/javascript" charset="{% static 'main.js' %}"> hello() </script> But this is giving me the following error: Uncaught ReferenceError: hello is not defined Why is this happening? Am i not importing the file? This is where main.js is located: static -> main.js And here is how my static directory is defined on Django: STATIC_URL = '/static/' My static directory contains a lot of other files and i'm not having problems with those; can someone help me find what i'm doing wrong with this one? Every advice is appreciated -
How to get only one object from ManyToOne table, instead of queryset?
Table Images: id| image | item_id 15|some/path| 45 16|some/path| 45 17|some/path| 45 First try: recommended_items = Item.objects.all().filter(rating__gte=9) // All my items (`item_id` column) for item in recommended_items : image = Images.objects.get(item=item.id)[:1] It works for first item with id=45 but for the rest it returns error: Images matching query does not exist. Second try: for item in recommended_items : image = Images.objects.filter(item=item)[:1] Now it works for all items, existing or not, but it returns iterate object and I should add for loop for just one object, like this: for i in image: print(i.image) What is the right way to handle this ? I want just one record (the last one if it is possible) -
Why am I getting this error while typing the command- makemigrations
from django.db import models # Create your models here. class Products(models.Model): title = models.TextField() description = models.TextField() price = models.TextField() I don't know why I get this error: Traceback (most recent call last): File "Blank/manage.py", line 21, in main() File "Blank/manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\core\management__init__.py", line 377, in execute django.setup() File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'products' -
DRF: how to change the value of the model fields before saving to the database
If I need to change some fields values before saving to database as I think models method clear() is suitable. But I can't call him despite all my efforts. For example fields email I need set to lowercase and fields nda I need set as null models.py class Vendors(models.Model): nda = models.DateField(blank=True, null=True) parent = models.OneToOneField('Vendors', models.DO_NOTHING, blank=True, null=True) def clean(self): if self.nda == "": self.nda = None class VendorContacts(models.Model): .... vendor = models.ForeignKey('Vendors', related_name='contacts', on_delete=models.CASCADE) email = models.CharField(max_length=80, blank=True, null=True, unique=True) def clean(self): if self.email: self.email = self.email.lower() serializer.py class VendorContactSerializer(serializers.ModelSerializer): class Meta: model = VendorContacts fields = ( ... 'email',) class VendorsSerializer(serializers.ModelSerializer): contacts = VendorContactSerializer(many=True) class Meta: model = Vendors fields = (... 'nda', 'contacts', ) def create(self, validated_data): contact_data = validated_data.pop('contacts') vendor = Vendors.objects.create(**validated_data) for data in contact_data: VendorContacts.objects.create(vendor=vendor, **data) return vendor views.py class VendorsCreateView(APIView): """Create new vendor instances from form""" permission_classes = (permissions.AllowAny,) serializer_class = VendorsSerializer def post(self, request, *args, **kwargs): serializer = VendorsSerializer(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) As I learned from the documentation Django Rest Framework serializers do not call the Model.clean when validating model serializers In dealing with this problem, I found two ways to … -
Django increasing value in database on update
i have table for inventory where is Qty column, i will like to add Qty using form to sum new value with already existed in database my class based view in views.py looks like : class ItemUpdateView(LoginRequiredMixin, UpdateView): model = Stock template_name = 'users/item_update_form.html' fields = ['qty'] right now im getting this output : screenshot from page view i will like to have empty Qty Field to type new value and after pressing Add increase value already existing in database with this new value -
Django Choice Field similar as in Admin (Permissions)
Unfortunately we have some really long drop down lists for our users to choose from and the way the django admin implemented their permissions ui really looks like a good solution for this, but for the life of me I can't find any examples how to implement something similar? Does anyone has any tipps? (I currently use "Select2MultipleWidget" to at least make it somewhat manageable) -
NOT NULL constraint failed: complaint_complaint.resident_id
I am writing an app in which people can submit their complaints related to some issues. After the form is submitted, it is supposed to redirect to the page where the details of the complaint are mentioned like area of the complaint, title, description etc. But after the form is submitted, it throws IntegrityError. I read about it and went through some of the solutions: Someone suggested that I delete some past migrations and run them again. I cleared the migrations, ran them again and made some posts through the admin but it is throwing the same error. Some posts suggest that null=True, blank=True should be added but I do not understand where they should be added in my case. I also don't want to add null=True, blank=True because I don't want any field to be left blank. Below is my models.py: from django.db import models from django.urls import reverse # Create your models here. class Complaint(models.Model): """ Details of the complaint """ resident = models.ForeignKey('auth.User', on_delete=models.CASCADE) AREA = [('PL', 'Plumbing'), ('EL', 'Electricity'), ('CP', 'Carpenter'), ('CO', 'Construction'), ('DS', 'Disputes'), ('OT', 'Other'),] matter = models.CharField(max_length=2, choices=AREA) title = models.CharField(max_length=200) text = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): … -
How to sent images through django sendmail
I'm trying to send images in a letter, but it doesn’t work out for me. I tuned {{ STATIC_URL }} but it did not help... How i can fix this? In settings: STATIC_URL = 'http://10.0.50.42:8103/static/' In HTML: <img src="{{ STATIC_URL }}dc/images/banner2.png"> With this setting, I started to receive a letter, but the images are not displayed there. -
Email sent from Django is not received
I have a website where I would like users to contact us if they need it. Thus, I wrote this views def contact(request): submitted = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): mail=request.POST.get('email') subject=request.POST.get('objet') msg=request.POST.get('message') send_mail(subject, msg, settings.EMAIL_HOST_USER,['med.abdillah@massiwatechnology.com'],fail_silently=False) return HttpResponseRedirect('/contact?submitted=True') else: form = ContactForm() if 'submitted' in request.GET: submitted = True return render(request, 'contact.html', {'form': form, 'submitted': submitted}) This views is based on the form bellow: class ContactForm(forms.Form): # nom_complet=forms.CharField(max_length=100, required=True) email=forms.EmailField(required=True) objet=forms.CharField(widget=forms.Textarea( attrs={ "rows":1, "cols":80 } )) message=forms.CharField( widget=forms.Textarea( attrs={ "class":"message two", "rows":5,"cols":80 } ) ) In my settings.py file I did the configurations bellow: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST='mail.massiwatechnology.com' EMAIL_PORT='465' EMAIL_HOST_USER='med.abdillah@massiwatechnology.com' EMAIL_USE_TLS=True # EMAIL_USE_SSL=False EMAIL_HOST_PASSWORD='mypassword' [ But I am no receiving any message in this email: med.abdillah@massiwatechnology.com. Is there any configurations mistakes, please? -
Django LoginView authenticate User
Good day. I'm trying to authenticate a user through a custom LoginView I can't understand how it works, whenever i try to authenticate, all it does is react on GET request. When i send a POST request it does nothing with it. I've overriden def post(self, request, args, kwargs) all i get are some strange errors. It doesn't react to form_valid either.. What can i do here? urls.py path('user/login/', CustomLoginView.as_view(), name='login'), forms.py class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(args, kwargs) username = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Email address', 'type': 'email', 'id': 'inputEmail'} ), label='') password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password', 'type': 'password', 'id': 'inputPassword'} ), label='') views.py class CustomLoginView(LoginView): authentication_form = LoginForm def get(self, request, *args, **kwargs): if self.request.user.is_authenticated: return super(CustomLoginView, self).redirect_authenticated_user return super(CustomLoginView, self).get(request, *args, **kwargs) def form_valid(self, form): super(CustomLoginView, self).form_valid(form) # data = form.cleaned_data # email = data['username'] # password = data['password'] # authenticate(self.request, username=email, password=password) # def post(self, request, *args, **kwargs): # form = LoginForm(self.request.POST) # self.form_valid(form) # cd = form.clean() # email = request.user.email # email = cd['email'] # password = cd['password'] # user = authenticate(request, email=email, password=password) # if user is not None: # login(request, user) # return redirect(self.get_success_url()) # return super(CustomLoginView, self).form_valid(form) … -
Using include to import all the urls from my django app
I'm learning Django and I think I'm following an old tutorial. What I'm trying to do right now is connect using the urls.py(in main app) all the urls from my other app. First of all, import the library include (and the others that where already). from django.contrib import admin from django.urls import path, include The write the url/path: urlpatterns = [ path('admin/', admin.site.urls), path('Platform_App', include('Platform_App/urls.py', namespace = 'Platform_App', app_name = 'Platform_App')), ] But reading the django information, I tried to do something like this that doesn't work, urlpatterns = [ path('admin/', admin.site.urls), path('Platform_App', include('Platform_App.urls')), ] How I have to do it correctly? Thank very much!!! -
django admin list custom button's click event
admin.py class TestAdmin(admin.ModelAdmin): class Media: js = ( 'js/common.js', ) list_display = ['custom_actions'] def custom_actions(self, obj): return mark_safe( '<a class="button call_alert" href="#" data-msg="A">A</a>&nbsp;' '<a class="button call_alert" href="#" data-msg="B">B</a>' ) custom_actions.short_description = 'Custom Actions' admin.site.register(Test, TestAdmin) js/common.js (function($) { $(".call_alert").on("click", function() { alert($(this).data("msg")); // ★★★ Dose not!!! ★★★ }); })($); error message : Uncaught TypeError: $ is not a function at common.js:2 at common.js:5 How can I get alert message? Is it impossible? Please help.. -
Display Text in Text Area Django
I'm new to Django and looking for a way to display terms and condition paragraphs in the Text area to view them on my home.html. Text for TextArea: To use the Online Services through U.S. Bank, you must: • Be a U.S. Bank customer with an eligible account; • Have and maintain valid log-in credentials (including a personal ID and password) for Online Services, which may be provided and revoked in our sole discretion; • Have and maintain a valid email address; • Agree to electronically accept this Agreement and notices regarding this Agreement; and • Use Online Services in accordance with the terms of this Agreement. Use of certain Online Services may require additional accounts or other eligibility requirements. Any help would be appreciated, Thanks in Advance -
Django Model DateField and input fixture
Model file includes : class Foo(models.Model): bar = models.DateTimeField() Fixture file.json includes: { "model": "app.Foo", "pk": "1", "fields": { "bar": "2018/4/20", } }, when I'm trying to add fixtures with "python manage.py loaddata" result is: django.core.serializers.base.DeserializationError: Problem installing fixture 'C:\Projects\TestProject\app\fixtures\file.json': ['“2018/4/20” value has an invalid format. It must be in Y YYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']: (app.Foo:pk=1) field_value was '2018/4/20' so my question is how can I add date format with "YYYY/MM/DD" to my Model files ? -
django: unexpected file download after redirect when file does not exist
Django==1.11.12 If the file exists, the view function creates StreamingHttpResponse and all is fine. But if the file does not exist, the view function should redirect. The problem is, it does not redirect but instead prompt up to ask to save as a file, which has the content of redirected html. import os from wsgiref.util import FileWrapper import mimetypes from django.http import StreamingHttpResponse from django.shortcuts import render, redirect try: response = StreamingHttpResponse( FileWrapper(open(file_path, 'rb'), chunk_size), content_type=mimetypes.guess_type(file_path)[0]) response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = "attachment; filename=a_file.xlsx") except FileNotFoundError as e: response = redirect("home") return response