Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework viewset and url mixup
In my project, i have 2 different viewset of the different serializer as both get query is different than each other. However, after applying the routers, when i go to check the API output, both API were using the same url instead. I did double check to make sure both serializer and views are different but i still get the same result. Moreover, there is another url which i create with 2 different view thus 2 different router yet it work as i wanted. Did i do something wrong ? Here is the screenshot of the output to get better understanding of what im talking about. Its really weird : https://imgur.com/a/PVfcu As u can see from my code below, in the url i specify 2 different viewset for different url however, only the schedule works, the user and family url however, got problem. Here is my code: serializer class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'userId', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'relationship', 'birthTime', 'bmi', 'height', 'weight', 'bloodtype', 'allergy') class Family2Serializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'userId', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'relationship', 'birthTime', 'bmi', 'height', 'weight', 'bloodtype', 'allergy') class Schedule2Serializer(serializers.ModelSerializer): valid_time_formats = ['%H:%M', '%I:%M%p', … -
Basic Django app index pathing syntax error
So I'm just getting started with Django and I decided to go through a tutorial that is a tad outdated in terms of syntax so I was wondering if someone could show me where I'm going wrong here and maybe provide a solution with the updated syntax :) Thanks in advance!! I'm running python 3.6 and Django 2.0.1 :) Here is the link to the tutorial: https://www.youtube.com/watch?v=iZ5my3krEVM skip forward to 13:10 for the syntax in question. here is my code: from django.urls import path from . import views urlpatterns = { path('', views.index, name='index')] and here is my output: File "/home/jon/Py_Dev/venv/Django-Projects/mysite/webapp/urls.py", line 5 path('', views.index, name='index')] ^ SyntaxError: invalid syntax -
Steps to work with django-jet-demo
I am trying to see django-jet-demo in action, i.e. https://github.com/geex-arts/django-jet-demo, but It didn't work. git clone https://github.com/geex-arts/django-jet-demo.git mkvirtualenv venv cd django-jet-demo pip install -r requirements/base.txt django makemigrations I have the errors 1- configparser.NoSectionError: No section: 'common' If I remove config.get(..., 'common') inside application/settings.py 2- configparser.NoSectionError: No section: 'email' If I remove config.get(..., 'email') inside application/settings.py 3- If I remove config.get(..., 'database') inside application/settings.com How could I fix this problem? What are the steps to make django-jet-demo works? -
"Apps aren't loaded yet" when trying to run pytest-django
Using the (partial) polls app from the Django tutorial as an example, I'm trying to get pytest-django to run. Using the command django-admin startproject mysite2, I've created a project directory with the following structure: . ├── db.sqlite3 ├── manage.py ├── mysite2 │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── polls │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py └── pytest.ini My pytest.ini looks like [pytest] DJANGO_SETTINGS_MODULE = mysite2.settings python_files = tests.py test_*.py *_tests.py Following the tutorial, in polls/models.py I've created Question and Choice models: import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Now, if I make tests.py as described in the tutorial, which is based on Python's built-in unittest module, import datetime from django.utils import timezone from django.test import TestCase from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): time = timezone.now() + … -
Queryset in a while loop django
I'm using the queryset below and i'm quite new to Database's i want to know if it's not too much expensive to do so or if it is, suggest an alternative way? while active_user is None: active_user = Users.objects.filter(is_active=True).first() the is_active field is indexed in database (db_index=True) and the while loop won't take more than 2-3 mins. using MySql. -
Django 2.0 throws AttributeError: ''Image' object has no attribute 'replace'"
When trying to set an html image to my static path + image path in Django 2.0, the django development server displays the following error: Error during template rendering In template /Users/arikanevsky/webappgit/ari/templates/ari/software.html, error at line 5 'Image' object has no attribute 'replace' The Image class from models.py: class Image(models.Model): """This class contains a reference to the ImageField. It is part of a base of models comprising the webapp. """ uplpath = '%Y/%m/%d' dfltpath = 'page_images/Y/M/D/no_img.jpg' image = models.ImageField(upload_to=uplpath, default=dfltpath) def __str__(self): """Return human readable string of self.image.""" return self.image.name The index method from views.py: def index(request): page_list = get_list_or_404(Page.objects.all()) return render(request, 'ari/index.html', {'page_list': page_list}) The index.html file (it is used as named): {% if page_list %} <ul> {% for page in page_list %} <a href="/ari/{{page.id}}/bio"><p>My bio page</p></a> <a href="/ari/{{page.id}}/career"><p>My career page</p></a> <a href="/ari/{{page.id}}/software"><p>My software page</p></a> <a href="/ari/{{page.id}}/publications"><p>My publication page</p>. </a> {% endfor %} </ul> {% else %} <p>No pages are available :(</p> {% endif %} The software method from views.py: def software(request, page_id): software_page = get_object_or_404(Page, pk=page_id) return render(request, 'ari/software.html', {'software_page': software_page}) The software.html file: {% load static %} <img src = "{% static software_page.image %}" alt = "Profile Picture"/> The app directory structure is the following: (I believe we … -
Django multiple inner join?
I want to show in a html the name of the city, state and country of a publication. But they are in diferent tables. Here is my models.py class country (models.Model): country_name = models.CharField(max_length=200, null=True) country_subdomain = models.CharField(max_length=3, null=True) def __str__(self): return self.country_name class countrystate (models.Model): state_name = models.CharField(max_length=200, null=True) country = models.ForeignKey(country, on_delete=models.CASCADE, null=True) importance = models.IntegerField(null=True) def __str__(self): return self.state_name class city (models.Model): city_name = models.CharField(max_length=200, null=True) countrystate = models.ForeignKey(countrystate, on_delete=models.CASCADE, null=True) def __str__(self): return self.city_name class publication(models.Model): user = ForeignKey(users, on_delete=models.CASCADE, null=False) title= models.CharField(max_length=300, null=True) country=models.ForeignKey(country, on_delete=models.CASCADE, null=True) countrystate=models.ForeignKey(countrystate, on_delete=models.CASCADE, null=True) city=models.ForeignKey(city, on_delete=models.CASCADE, null=True) def __str__(self): return self.title And I want to show the country_name, countrystate_name and city_name in my HTML template. Here is my views.py def publications(request): mypublications = publication.objects.filter(user_id=request.session['account_id']) dic.update({"plist": mypublications }) return render(request, 'blog/mypublications.html', dic) and Here is my mypublications.html {% for pub in plist %} <div> <a href="{{ pub.id }}"> {{ pub.title }} </a> <p>{{ pub.county_name }}</p> HERE IS WHERE I WANT TO GET THE COUNTRY NAME, NOT THE COUNTRY ID <p>{{ pub.state_name }}</p> <p>{{ pub.city_name }}</p> </div> {% endfor %} but this not work. I put pub.country_id and it works but I want the name of the country. The same for state … -
React js and Django-rest-framework ( Getting request.user )
So i have created a django api view that maps to a url: http://127.0.0.1:8000/api/user/request/ to show the requst.user's username. However whenever i get this data from loadData in reactjs it sends back an empty string '', showing that there is no requested user/no user logged in. regardless if a user has logged in or not. BTW the django development server and react development server are separate, not sure if this matters? Reactjs class Wrapper extends Component { state = { requestUser: null } componentDidMount () { this.loadData() } loadData () { axios.get('http://127.0.0.1:8000/api/user/request/').then(response => { this.setState({ requestUser: response.data }); console.log(response.data) }) } } Django api view class RequestUserAPIView(APIView): def get(self, request, format=None): data = { "request_user": request.user.username } return Response(data) Url url(r'^user/request/$', RequestUserAPIView.as_view(), name='request_user'), -
django rest framework list DryPermissions
I have a django rest endpoint that returns a list and detail view. For the detail view I can use the function has_object_read_permission() in the model to check permissions. However, for the list view it is all or nothing as only has_read_permission() in the model is checked. I would like to limit the data in the entries without permissions in the list so it does not return more information than it should. For the individual entries in a rest endpoint list, the permissions can be checked and I can also include them in the entries if I include can be checked if I include permission_classes = (DRYPermissions,) in the viewset. My question is what is the best way to limit the entries without permission to yield something like this where the entries without permission have some fields deleted (or blanked) GET /rest/example/948/ HTTP 200 OK Allow: GET, PUT, PATCH, DELETE, OPTIONS Content-Type: application/json Vary: Accept { "id": 948, "permissions": { "read": true, "write": true }, name: "example 1", field1: 1, field2: 2, field3: 3, field4: 4, } { "id": 947, "permissions": { "read": false, "write": false }, name: "example 2", } would I modify them in the serializer or do … -
Have a UserProfile Objects, which then has a field that is a foreignkey to Team object. How to query the Team?
Here's what i'm trying to accomplish: I would like the page to show what the team object has thats related to that profile. Here are the models: class UserProfile(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) team = models.ForeignKey(Team, on_delete=models.CASCADE,) phone = models.CharField(max_length=11) class Team(models.Model): name = models.CharField(max_length=10) Here is the views.py: def userpage(request): """The home page""" profile = UserProfile.objects.filter(owner=request.user) team = Team.objects.get(------>?WHAT GOES HERE?<-----) context = { 'team': team, 'profile': profile } return render(request, 'app/userpage.html', context) Edit: Is this how I should even approach this? Or is the proper way to approach this is to just have the profile context and in the template access the team fields e.g. {{ profile.team.name }} -
Can't load template from an Angular route in a Django project
In my urls.py, I have the following patterns: url(r'^$', views.index, name='index'), url(r'^setup/$', views.index, name='index'), Both the patterns ultimately resolve to the same view, as the logic is handled in the Controllers. The view kinda looks like something like this: def index(request): return request(request, 'index.html', {}) In my index.html file, I load in Angular, my Angular App, the routes, and everything else. My angular routes look something like this: .when('/', { controller : 'BaseController', templateUrl : 'static/app_partials/base.html', reloadOnSearch: false }) .when('/products/', { controller : 'ProductsController', templateUrl : 'static/app_partials/products.html', reloadOnSearch: false }) Now, when I go to the first URL in my pattern, everything works nicely, and the route is able to load the template perfectly, as the url is http://example.com/static/app_partials/base.html, which is exactly where the file is. However, the second URL does not work, as the template being called now is http://example.com/setup/static/app_partials/base.html, which does not exist. How can I fix this issue? I have tried to put the whole URL in my routes, with the domain and stuff, but then I get a insecure URL error. Any help? Thanks. -
Loop Through Every Model In Django Project
In django, is there a way to loop through each model that is currently in your database? I would like to be able to have a function that gets the total number of rows in all of my models, per model, without having to the function every time I added a new model. the output being something like model1 rows: 23 model2 rows:234 and then if I were to add a new model it would automatically output model1 rows: 23 model2 rows:234 model3 rows:0 the ideal format would be something like. def getDbStatus() for m in Models: print(m.objects.count) -
How to annotate count of an already annotated value?
I have a model named Order with a timestamp_delivered (datetime field). Model Order is having a driver associated with it. I want to get number of days each driver has delivered orders. I am trying below query: Order.objects.annotate(date=Cast('timestamp_delivered'), DateField()).values('driver_id').annotate(days=Count('date')) but got the error: KeyError: date Tried running below command as well: Order.objects.values('driver_id').annotate(date=Cast('timestamp_delivered'), DateField()).annotate(days=Count('date')).values_list('driver_id', 'days') Got the output [(Driver1, 1), (Driver2, 1), (Driver2, 1)... ] Output I am expecting is something like in formar: [(Driver1, 2), (Driver2, 4), (Driver3, 8)... ] -
Redirecting users signing in with social accounts
I am using Django allauth for sign up and social authentication. For users signing up with there email, they are redirected normally to their profile based on their username as the slug. For example, something like this: views.py class RegisterView(SignupView): form_class = RegisterForm template_name = 'oauth/auth_form.html' def form_valid(self, form): return redirect('profiles:Index', slug=form.cleaned_data['username']) The user is redirected to the profiles app which contains an Index view that displays their profile based on the slug (their username inputted). This works correctly, however, when I try to do social sign in with Facebook or Google for example, it redirects me to /accounts/profile/# which is the default Django profiles page. I want them to be redirected to the profiles app, which is /profiles/{their username} How can I make this happen? -
Django posts not executing well
I type this code in my index.html: Im an index page. {% for post in posts %} <div> <h3>{{ post.title }}</h3> <p>{{ posts.summary }}</p> </div> {% endfor %} and when i execute it i, my page looks like this enter image description here -
Django is_valid() failure
I tried several ways but is_valid() always returns false. Not sure why. I copied nearly whole syntax for better understanding but I don´t you need all that code. I really would be thankful for having help. Thanks! html: {% csrf_token %} {{ FirstContactForm.message }} forms: class FirstContactForm(forms.ModelForm): firstName = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Vorname', } )) imagine some more forms but cut them out for better overview message = forms.CharField(widget=forms.Textarea( attrs={ 'class': 'form-control', 'rows': '4', 'id': 'exampleFormControlTextarea1', 'maxlength': 2000, } )) class Meta: model = ContactForm fields = ('vorname', 'nachname', 'email', 'nummer', 'handyNummer', 'nachricht',) views class Contact(TemplateView): template_name = 'contact.html' context = { 'FirstContactForm': FirstContactForm, } def get(self, request): return render(request, self.template_name, self.context) def post(self, request): form = FirstContactForm(request.POST) text = form.cleaned_data['vorname'] if form.is_valid(): form = FirstContactForm(commit=False) form.save() text = form.cleaned_data['vorname'] form = FirstContactForm() return redirect('index') args = {'FirstContactForm': FirstContactForm, 'text': text} return render(request, self.template_name, args) model: class ContactForm(models.Model): vorname = models.CharField(max_length=400) nachname = models.CharField(max_length=400) email = models.CharField(max_length=400) nummer = models.CharField(max_length=400) handyNummer = models.CharField(max_length=400) nachricht = models.CharField(max_length=2000) -
NoReverseMatch not matching key argument
I have a response error that is driving me crazy, I tried everything but no way to find why am I getting that error : django.urls.exceptions.NoReverseMatch: Reverse for 'team_select' with keyword arguments '{'pk1': ''}' not found. 1 pattern(s) tried: ['website/project/(?P<pk1>[0-9]+)/linkteam2/$'] that is my views: class HomePage(TemplateView): template_name= 'index.html' class LinkTeam(generic.ListView): template_name = 'link_project.html' def get_queryset(self): #import pdb; pdb.set_trace() #team2 = Team.objects.all().filter(team_hr_admin = self.request.user) queryset = Team.objects.filter(team_hr_admin=self.request.user) return queryset def TeamSelect(request): import pdb; pdb.set_trace() if request.method == "POST": select_form = EditSelectTeam(request.user, request.POST) if select_form.is_valid(): data = select_form.cleaned_data['team_choice'] obj2 = Project.objects.filter(project_hr_admin=request.user) obj3 = obj2.latest('id') if obj3.team_id == None: obj3.team_id = data obj3.save() obj4 = obj3.team_id obj5 = obj4.members.all() for i in obj5: current_site = get_current_site(request) message = render_to_string('acc_join_email.html', { 'user': i.first_name, 'domain':current_site.domain, }) mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app' to_email = i.email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() messages.success(request, 'test') return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':obj3.id})) else: print('this project has already a team') else: print('Non Valid form') else: select_form = EditSelectTeam(request.user) return render(request,'link_project.html', {'select_form':select_form }) class HRIndex(generic.ListView): #import pdb; pdb.set_trace() template_name = "HR_index.html" model = Project class CandidateIndex(TemplateView): #import pdb; pdb.set_trace() template_name = "candidate_index.html" class EmployeeIndex(TemplateView): #import pdb; pdb.set_trace() template_name = "employee_index.html" def get_context_data(self, **kwargs): … -
Add A New Field To Existing Model - django.db.utils.ProgrammingError: column {field} does not exist
models.py I have a Scorecard model that has a ManyToManyField to another model named Account: class Scorecard(models.Model): .... name = models.CharField(max_length=100) accounts = models.ManyToManyField(Account) ... def __str__(self): return self.name My Account class currently has four fields (account_name, adwords_account_id, bingads_account_id, label). class Account(models.Model): account_name = models.CharField(max_length=100) adwords_account_id = models.CharField(max_length=10, blank=True) bingads_account_id = models.CharField(max_length=15, blank=True) # gemini_account_id = models.CharField(max_length=15, blank=True) label = models.CharField(max_length=30, blank=True) def __str__(self): return self.account_name Notice that field gemini_account_id is commented out. I want to add this field to the model. If I leave gemini_account_id commented out and runserver, everything works fine. If I then uncomment gemini_account_id and do python manage.py makemigrations (venv) C:\Django\scorecard>python manage.py makemigrations FULL ERROR Traceback (most recent call last): File "C:\Django\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column scorecards_account.gemini_account_id does not exist LINE 1: ...t_id", "scorecards_account"."bingads_account_id", "scorecard... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Django\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Django\venv\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Django\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Django\venv\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Django\venv\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready self.module.autodiscover() File "C:\Django\venv\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', … -
Static Root - Django version 2.0.1
Upgraded from Django 1.10 to 2.01. Settings.py (Has not changed) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = os.path.join('/processor/', 'static/') python manage.py collectstatic & python manage.py runserver both return the same errors below: hal@hal:~/CSsite$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Django version 2.0.1, using settings 'CSsite.production' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [ERROR] (Thread-1 ) Internal Server Error: / Traceback (most recent call last): File "/home/hal/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hal/CSsite/processor/views.py", line 108, in index return render(request, 'processor/select.html', dic) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/backends/django.pstaticfilesy", line 61, in render return self.template.render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 175, in render return self._render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 167, in _render return self.nodelist.render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 943, in render bit = node.render_annotated(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated return self.render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/templatetags/static.py", line 106, in render url = self.url(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/templatetags/static.py", line 103, in url return self.handle_simple(path) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/templatetags/static.py", line 118, in … -
django-crontab does not execute scheduled jobs
I am having a very similar virtualenv setup than in the question: Django crontab not executing test function. in my_app.cron.py def test(): print('HELLO') in settings.py INSTALLED_APPS = ( ... 'django_crontab', ) CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/1 * * * *', 'my_app.cron.test','>> /cron_job.log'), ] python manage.py crontab add adding cronjob: (bee8ad945bb9c6b15a3ff0847481a181) -> ('*/1 * * * *', 'my_app.cron.test', '>> /cron_job.log') python manage.py crontab show Currently active jobs in crontab: bee8ad945bb9c6b15a3ff0847481a181 -> ('*/1 * * * *', 'my_app.cron.test', '>> /cron_job.log') Everything seems fine yet nothing is printed in the log file or the console. What's missing here? -
userprofile-0-id Error , working with Django inline_formset
i am trying to let my site's users to edit their own profile pages, where that page contains information from poth "User model" & "UserProfile model", using django inline_formset, but i am encountering,userprofile-0-id error when submiting the form . models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(default=0) image = models.ImageField(upload_to="profile_image", blank=True) description = models.CharField(max_length=200, default='') category = models.CharField(max_length=600, default='') website = models.URLField(default='', blank=True) forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'last_name', 'email'] views.py @login_required() # only logged in users should access this def edit_user(request, pk): # querying the User object with pk from url user = User.objects.get(pk=pk) # prepopulate UserProfileForm with retrieved user values from above. user_form = UserForm(instance=user) # The sorcery begins from here, see explanation below ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('website', 'description', 'phone','category','image',)) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: if request.method == "POST": user_form = UserForm(request.POST, request.FILES, instance=user) formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user) if formset.is_valid(): created_user.save() formset.save() return HttpResponseRedirect('/accounts/profile/') return render(request, "accounts/update.html", { "noodle": pk, "noodle_form": user_form, "formset": formset, }) else: raise PermissionDenied update.html <form action="." method="POST"> {% csrf_token %} <div class="form-row"> <div class="col"> <label for="Firstname">Vender Name</label> {% render_field … -
Can't create an object in django when field is a file
I'm using the last version of django and also I use Postgresql. I have a model called Subidos: class Subidos(models.Model): ramo = models.CharField(max_length=100) tipo = models.CharField(max_length=100) anyo = models.CharField(max_length=100) semestre= models.CharField(max_length=100) archivo = models.FileField(upload_to='pendientes/', null=True) def __str__(self): return '%s %s %s %s' % (self.ramo, self.tipo, self.anyo, self.semestre) As you see, archivo is a file. Now, my html form receive all this parameters (Works fine): <form method="post" action="{% url 'materialfdi:subir2' %}" enctype="multipart/form-data">{% csrf_token %} <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2" for="inputHelpText">Ramo</label> <div class="col-lg-6"> <input type="text" class="form-control" id="nombre_ramo" name="ramo" placeholder="Ejemplo: Bases de datos CIT"> <span class="help-block">Si existe el mismo ramo en distintas escuelas, por favor aclara a cual pertenece.</span> </div> </div> <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2" for="inputHelpText">Tipo de archivo</label> <div class="col-lg-6"> <input type="text" class="form-control" id="tipo_archivo" name="tipo" placeholder="Ejemplo: Semestre 2"> </div> </div> <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2" for="inputHelpText">Año del material</label> <div class="col-lg-6"> <input class="form-control" id="anyo" name="anyo" placeholder="Ejemplo: 2017" type="number"> </div> </div> <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2">Semestre del material</label> <div class="col-lg-6"> <select class="form-control mb-3" name="semestre"> <option>Primer semestre</option> <option>Segundo semestre</option> </select> </div> </div> <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2">File Upload</label> <div class="col-lg-6"> <div class="fileupload fileupload-new" data-provides="fileupload"> <div class="input-append"> <div class="uneditable-input"> <i class="fa … -
how to run celery with django on openshift 3
What is the easiest way to launch a celery beat and worker process in my django pod? I'm migrating my Openshift v2 Django app to Openshift v3. I'm using Pro subscription. I'm really a noob on Openshift v3 and docker and containers and kubernetes. I have used this tutorial https://blog.openshift.com/migrating-django-applications-openshift-3/ to migrate my app (which works pretty well). I'm now struggling on how to start celery. On Openshift 2 I just used an action hook post_start: source $OPENSHIFT_HOMEDIR/python/virtenv/bin/activate python $OPENSHIFT_REPO_DIR/wsgi/podpub/manage.py celery worker\ --pidfile="$OPENSHIFT_DATA_DIR/celery/run/%n.pid"\ --logfile="$OPENSHIFT_DATA_DIR/celery/log/%n.log"\ python $OPENSHIFT_REPO_DIR/wsgi/podpub/manage.py celery beat\ --pidfile="$OPENSHIFT_DATA_DIR/celery/run/celeryd.pid"\ --logfile="$OPENSHIFT_DATA_DIR/celery/log/celeryd.log" & -c 1\ --autoreload & It is a quite simple setup. It just uses the django database as a message broker. No rabbitMQ or something. Would a openshift "job" be appropriated for that? Or better use powershift image (https://pypi.python.org/pypi/powershift-image) action commands? But I did not understand how to execute them. Help is very appreciated. Thank you -
Django, Axax PUT 400 Bad request
I have a problem with Django (rest) and ajax, when I try to send the data of a form with the method (PUT), in the browser console sends me an error (PUT '/ url / api / 1', 400 Bad request) , before coming and ask I started to investigate about this error and in many other posts give as a solution to use "JSON.stringify" to convert to json the form with the data to update, I have tried this and it did not work, another is use - contentType: "application / json; charset = utf-8", - but it did not work either, someone who can help me? my views.py class pacienteDetail(APIView): def get_object(self, pk): try: return modelsHC.Paciente.objects.get(pk=pk) except modelsHC.Paciente.DoesNotExist: raise Http404 def get(self, request, pk, format=None): paciente = self.get_object(pk) serializer = pacienteSerializer(paciente) return Response(serializer.data) def put(self, request, pk, format=None): paciente = self.get_object(pk) serializer = pacienteSerializer(paciente, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): paciente = self.get_object(pk) paciente.delete() return Response(status=status.HTTP_204_NO_CONTENT) class pacientesList(generics.ListCreateAPIView): queryset = modelsHC.Paciente.objects.all() serializer_class = pacienteSerializer permission_classes = (IsAuthenticated, ) def list(self, request): queryset = self.get_queryset() serializer = pacienteSerializer(queryset, many=True) return Response(serializer.data) def perform_create(self, serializer): serializer.save(user=self.request.user) my form.html <form class="form-edit" action="{% url … -
django login_required decorator does not work with ip 127.0.0.1
I have created a login system the view is as follows: def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request,user) return redirect('home:index') else: form = AuthenticationForm() return render(request,'accounts/login.html',{'form':form}) and added a login_required decorator to the home page as follows: @login_required(login_url="/login/") def index(request): return render(request, 'home/index.html', context) the problem is when I access the index page with localhost:8000/home/ the page is redirected correctly to the login page but with 127.0.0.1:8000/home/ the home page is rendered and i am not redirected to the login page! any solution? thanks in advance!