Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - get only year since the date
Code I'm working with: #models.py class Profile(models.Model): date_of_birth = models.DateField(null=True, blank=True) #template.html <span>Age: <small>{{ object.date_of_birth|timesince }}</small></span> That code gives me for example: 25 years, 3 months. What should I do to that field give me only years? (In this case 25) Any ideas? Thanks. -
Assign users and permissions to object BY FORM
Django object permissions is a nice way to assign permissions to users on a object level. Often an object has one owner, and this is set when the object is created. Sometimes there are some admin/superusers that assign rights, which works if this doesn't occur often and several trusted users can handle this workload via the django.contrib.admin interface However, an object often starts with one 'owner', whoever created it. That owner might want her/his friends to join and readers, writers or whatevers. Examples are: github repositories, where the original user can add collaborators, and whatsapp groups, where the creator can add others to join. Does django provide a form, widget or form field to assign users and permissions to an objects (opposite of the django admin form, that assigns objects and permissions to a user)? Something like this: This particular example autocompletes from a potentially huge database of users, allows you to delete them and set a specific permission (sort of cumulative, since write implies read) This seemed like a common use case, but I couldn't find anything in django or as a django app. -
Django: OneToOne relation with abstract class Python
I have something like this in my django-database: class Parent(models.Model): id = models.AutoField(primary_key=True) ... class ParentA(Parent): A_attr = models.IntegerField(...) ... class ParentB(Parent): B_attr = models.CharField(...) ... Now I would like to add class Child with OneToOneField(Parent), but django shows me error: (fields.E300) Field defines a relation with model 'Parent', which is either not installed, or is abstract. I saw some "not-so-bad" solutions, but the biggest problem is that I'm not allowed to modify any existing classes. I know I can simply add ChildA(ParentA) and ChildB(ParentB) but this solution is not very exciting for me. I would be gratefull for any advice. -
Django many to many with additional field not working
I am new to Django and followed this to write my models.py file: class Coin(models.Model): name = models.CharField(max_length=50, unique=True) class Meta: verbose_name = 'coin' verbose_name_plural = 'coins' ordering = ['name'] def __str__(self): return self.name class PublicPortfolioManager(models.Manager): def get_queryset(self): qs = super(PublicPortfolioManager, self).get_queryset() return qs.filter(is_public=True) class Portfolio(models.Model): title = models.CharField('title', max_length=255) date_created = models.DateTimeField('date created') date_updated = models.DateTimeField('date updated') is_public = models.BooleanField('public', default=True) owner = models.ForeignKey(User, verbose_name='owner', related_name='portfolio') coins = models.ManyToManyField(Coin, through='CoinInfo') objects = models.Manager() public = PublicPortfolioManager() def __str__(self): return '%s' % (self.title) def save(self, *args, **kwargs): if not self.id: self.date_created = now() self.date_updated = now() super(Portfolio, self).save(*args, **kwargs) class CoinInfo(models.Model): coin = models.ForeignKey(Coin) portfolio = models.ForeignKey(Portfolio) amount = models.FloatField(default=0.0) #date_purchased = models.DateTimeField(auto_created=True) Everything works as it should except when I want to save an instance of CoinInfo, then I get the following error: table hello_coininfo has no column named coin_id. I already flushed the database and ran makemigrations and migrate before creating the instances. What I am doing wrong? -
Django with oracle error. ORA--0001: Message -1 not found
I have a problem with a Django project using Oracle for quite some time which i cannot solve.This is my first work on oracle database but i will try to explain as best as i can. I have developed a tool in my work for users to be able to massively update records(Just Update).The data are presented and filtered using ajax. There is also an oracle procedure created by someone else than inserts some records to the tables. But often the tool stop working throwing the following: DatabaseError: ORA--0001: Message -1 not found; product=RDBMS; facility=ORA I tried everything and i searched everywhere for months but with no luck. At first i saw that the sequence nextval was behind max ID by using triggers and sequences and changed that for the id to get nextval when the procedure inserts records ensuring unique id but after that max ID and nextval are ok but the error persists.We looked about constraint violation during insert but i don't think that's the case cause the primary key - unique id is incremented correctly and we dont get error from oracle logs. I know ora--0001 is unique key constaint violation i've been searching and trying things … -
Django Pagination Does Not Working
my problem is , views.py from django.shortcuts import render from django.utils import timezone from Blog.models import Makale,Kategori,Profil from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger def index(request): posts = Makale.objects.all().order_by('-tarih') paginator = Paginator(posts,1) page = request.GET.get('page') try: sayfalar = paginator.page(page) except PageNotAnInteger: sayfalar = paginator.page(1) except EmptyPage: sayfalar = paginator.page(paginator.num_pages) return render(request,'index.html',{'posts':posts}, {'sayfalar':sayfalar}) index.html <div class="pagination"> <ul> <li><span class="nav-prev">{% for sayfa in sayfalar %}{% if sayfalar.has_previous %}<a href="?page={{ sayfalar.previous_page_number }}">Önceki</a>{% endif %}{% endfor %}</span></li> <li><span class="current">{{ sayfalar.number }}</span></li> <li><span class="nav-prev">{% for sayfa in sayfalar %}{% if sayfalar.has_next %}<a href="?page={{ sayfalar.next_page_number }}">Sonraki</a>{% endif %}{% endfor %}</span></li> </ul> </div> This code does not work, when it worked this code, result empty what should I ? -
Django Internationalization - Language not change
I have already searched on many post but none could solve my problem. My settings.py : from os import path PROJECT_ROOT = path.abspath(path.dirname(__file__)) LOCALE_PATHS = (path.join(PROJECT_ROOT, '/conf/locale/'),) TIME_ZONE = 'UTC' LANGUAGE_CODE = 'fr-fr' USE_I18N = True USE_L10N = True gettext = lambda x: x LANGUAGES = ( ('fr', gettext('French')), ('en', gettext('English')), ) urls.py : from django.conf.urls import * urlpatterns = patterns ('', ... url(r'^i18n/', include('django.conf.urls.i18n')), ) template.html (reduced version) : <div id="header"> ... {% include 'i18n.html' %} </div> i18n.html : {% load i18n %} {% trans "Une ligne de test" %} <form action="/i18n/setlang/" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }} /> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go" /> </form> I know this code has already appeared in many other posts but none solutions helped me. My problem is that when i submit the form, the page reloads but the dropdown return on "French". Furthermore, when i try an obsolete translation in /locale/fr/LC_MESSAGES/django.po … -
Django AttributeError
I keep getting Attribute Error 'NoneType' object has no attribute 'get' It points to: order_number = response.get('order_number',0) Here are the related files in my checkout app. views.py: def show_checkout(request,): template_name='checkout.html' if cart.is_empty(request): cart_url = urlresolvers.reverse('show_cart') return HttpResponseRedirect(cart_url) if request.method == 'POST': postdata = request.POST.copy() form = CheckoutForm(postdata) if form.is_valid(): response = checkout.process(request) order_number = response.get('order_number',0) error_message = response.get('message','') if order_number: request.session['order_number'] = order_number receipt_url = urlresolvers.reverse('checkout_receipt') return HttpResponseRedirect(receipt_url) The checkout.py response is referring to: def get_checkout_url(request): return urlresolvers.reverse('checkout') def process(request): order = create_order(request) results = {'order_number':order.id,'message':''} postdata = request.POST.copy() amount = cart.cart_subtotal(request) def create_order(request): order = Order() checkout_form = CheckoutForm(request.POST, instance=order) order = checkout_form.save(commit=False) order.user = None order.status = Order.SUBMITTED order.save() if order.pk: cart_items = cart.get_cart_items(request) for ci in cart_items: oi = OrderItem() oi.order = order oi.quantity = ci.quantity oi.price = ci.price # now using @property oi.menuitem = ci.menuitem oi.save() # all set, empty cart cart.empty_cart(request) # return the new order object return order The Order() in the create_order module refers to the Order model I have in my checkout app. Thanks! -
Django select a valid choice error in form when using custom form template
I've been lurking for an answer for quite some time now, but I haven't found solution for my problems. I made custom template for my form and now, when I try to submit form I get this under choice field: Select a valid choice. is not one of the available choices. I believe that problems is because I am not passing instance of organization but id. I tried {{ form.instance.organization }} and then I get None where should be choice field views.py: class AddNewView(generic.View): formClass = AddNewForm template_name = 'myapp/subscription_form.html' def get(self, request): groups = self.request.user.groups.values_list('id', flat=True).first() form = self.formClass(groups, None) return render(request, self.template_name, {'form': form}) def post(self, request): groups = self.request.user.groups.values_list('id', flat=True).first() form = self.formClass(groups, request.POST) if form.is_valid(): subscription = form.save(commit=False) organization = request.user.groups.values_list('id', flat=True).first() input_user = self.request.user stuff = form.cleaned_data['stuff'] description = form.cleaned_data['description'] subscription.save() return render(request, self.template_name, {'form': form}) forms.py: class AddNewForm(forms.ModelForm): def __init__(self, groups,*args,**kwargs): super (AddNewView, self ).__init__(*args,**kwargs) self.fields['organization'].queryset = Organization.objects.filter(group=groups) class Meta: model = Subscription fields = [ 'organization', 'stuff', 'description', ] models.py: class Organization(models.Model): d_number = models.CharField(max_length=25) city = models.CharField(max_length=100) group = models.ManyToManyField(Group, help_text="groups") class Subscription(models.Model): organization = models.ForeignKey(Group, help_text="which organization") input_user = models.CharField(max_length=150) input_date = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=1000, null=True, blank=True, help_text='Description') stuff = … -
How can my django app access s3 bucket file mounted on ec2 instance
In order to give my video uploaded on s3 bucket "AS" in input for a bash script in my django view, i have mounted the s3 bucket on '/mnt' in my ec2 instance using s3fs. Now when i try the following: def getor(request): # get video from the s3 bucket mounted v = '/mnt/fold/media/videos/wtm/bbb5000.mp4' # process subprocess.call("./step2.sh %s" % (str(v)), shell=True) return render(request, 'endexecut.html') Problem: I can't access the video, i found the following error on my log : "/mnt/myfold/media/videos/wtm/bbb5000.mp4: Operation not permitted". P.s: I have mounted the bucket using the option -o allow_others, and the iam user has full access to s3 permission, i tried to set permissions on folder but i couldn't. -
Django rest framwork unable to save multiple instances because of weird error confusing dict and list?
I'm using DRF 3.6 to try to save a serialized list of Product instances, and am getting an error when calling serializer.save(). Here's the ViewSet create method: def create(self, request): serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list)) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) In the second line I'm trying to account for the many kwarg. Debugging the isinstance() call shows that it is True. Traceback below: File "django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 215, in _get_response response = response.render() File "django/template/response.py", line 107, in render self.content = self.rendered_content File "rest_framework/response.py", line 72, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "rest_framework/renderers.py", line 703, in render context = self.get_context(data, accepted_media_type, renderer_context) File "rest_framework/renderers.py", line 676, in get_context 'post_form': self.get_rendered_html_form(data, view, 'POST', request), File "rest_framework/renderers.py", line 509, in get_rendered_html_form return self.render_form_for_serializer(serializer) File "rest_framework/renderers.py", line 517, in render_form_for_serializer serializer.data, File "rest_framework/serializers.py", line 534, in data ret = super(Serializer, self).data File "rest_framework/serializers.py", line 267, in data self._data = self.get_initial() File "rest_framework/serializers.py", line 404, in get_initial for field_name, field in self.fields.items() File "rest_framework/serializers.py", line 405, in if (field.get_value(self.initial_data) is … -
Run django in docker with pycharm
I am trying to use PyCharm for remote debugging in my django project. I have created a Dockerfile: FROM python:3.6 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] And successfully used docker build -t dockering . to create image. I can view it: $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 58e102ea8aaf dockering:1.0 "python -u /opt/.p..." 11 minutes ago Created peaceful_babbage b10984d7f177 9adf577a7852 "python manage.py ..." 12 minutes ago Exited (137) 8 minutes ago And run it with docker run -p 8000:8000 and enter successfully my localhost:8000. When I try to do this in PyCharm however, it seems to bee unable to find correct image. I have set up proper interpreter in settings: And set up command: However, when I try to run it I have: 890e40a906dd:python -u /opt/project/manage.py runserver localhost:8000 Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 01, 2017 - 08:47:56 Django … -
Many to many model connection
So i have following models: Session, Rider. Basically now i want to have results where rider was placed in each session so basically its M:N connection (each rider is in many sessions, and each session have many riders). Now should i make new model called something like SessionResult? and place both foreign keys from Session and Rider and add a position field to this midtable? Or what is your recommendation? Here is model: class Rider(models.Model): first_name = models.CharField(_('First name'), max_length=100, db_index=True) last_name = models.CharField(_('Last name'), max_length=100, db_index=True) number = models.IntegerField(_('Rider number')) team = models.ForeignKey(Team) country = CountryField() birthday = models.DateField(_('Birthday')) birth_place = models.CharField(_('Birth place'), max_length=100) weight = models.IntegerField(_('Weight')) height = models.IntegerField(_('Height')) info = models.TextField(_('Info')) class Session(models.Model): title = models.CharField(_('Title'), max_length=100, db_index=True) event = models.ForeignKey(Event) start_date = models.DateTimeField(_('Start time')) end_date = models.DateTimeField(_('End time')) so something like this? class SessionResult(models.Model): rider = models.ForeignKey(Rider) session = models.ForeignKey(Session) position = models.IntegerField() time = models.TimeField() -
Postgresql & django Error- Connection refused tIs the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
I have been struggling at this problem for several days. Perviousy, I have compiler source code from OpenPLM and running successfully in Debian 6. However, I observed some Alert Mails could not be send out recently. I checked the log and find some error as below. It seems that the connection to PostgreSQL was not successful. I googled it and tried to find solution by setting below, but it still did not work. I am wondering if any one can help me to find the problem. Any advice and suggestion is highly appreciated. Regards, Dean. System Configuration 1. sourcecode: http://www.openplm.org/docs/2.0/en/admin/ht_1_install_server.html 2. OS: Debian 6 32 bit 3. PostgreSQL: 9.1 4. firewall is off 5. port 5432 is on. enter postgresql.conf listen_addresses = '*' port = 5432 pg_hba.conf local all all md5 host all all 0.0.0.0/0 md5 host all all ::/0 md5 ====================Error Message==================== root@openplm:/var/log/celery# cat w1.log [2017-08-01 16:06:22,702: ERROR/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection... Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer.py", line 390, in start self.consume_messages() File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer.py", line 474, in consume_messages readers[fileno](fileno, event) File "/usr/local/lib/python2.7/dist-packages/kombu/connection.py", line 292, in drain_nowait self.drain_events(timeout=0) File "/usr/local/lib/python2.7/dist-packages/librabbitmq/init.py", line 220, in drain_events self._basic_recv(timeout) ConnectionError: server connection error 320 message: CONNECTION_FORCED … -
Celery task not registering in django database
I am working on celery beat task and task is working fine (running properly on scheduled time) but i am not able to see task in my admin page and all celery related tables are empty in my PostgreSQL database (ex django_celery_beat_periodictask) what i am missing here ?? Requirement Django==1.9.7 python==3.5 celery==4.1.0 django-celery-beat==1.0.1 Project Tree advocate | drive | -- celery.py -- tasks.py celery.py from __future__ import absolute_import, unicode_literals from celery import Celery from celery.schedules import crontab import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'advocate.settings') # app = Celery('drive', broker='redis://localhost:6379/0') app = Celery('drive', broker='redis://localhost:6379/0', include=['drive.tasks']) app.control.purge() app.config_from_object('django.conf:settings', namespace='CELERY') # crontab for test app.conf.beat_schedule = { 'Emails-Every-Mon_Wed_Fri': { 'task': 'drive.tasks.weekly_task', 'schedule': crontab(minute='*/5'), }, } app.conf.timezone = 'UTC' # Optional configuration, see the application user guide. app.conf.update( result_expires=3600, ) app.autodiscover_tasks() if __name__ == '__main__': app.start() Run Command Used celery -A drive worker -B --loglevel=debug -S django -
Access child model attributes in django templates
I have created model inheritance in django models like: models.py class Instance(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, related_name='instances') name = models.CharField(max_length=255, name='name') slug = AutoSlugField(populate_from='name', unique=True) created_at = models.DateTimeField(default=timezone.now, editable=False) type = models.CharField(max_length=255, name='type', default='') class Meta: ordering = ['-created_at'] class CustomInstance(Instance): serverCode = models.TextField(default='', blank=False) jsonPackageCode = models.TextField(default='', blank=False) type = models.CharField(max_length=255, name='type', default='custom') class AwdInstance(Instance): archive = models.FileField(upload_to='archives', name='archive') type = models.CharField(max_length=255, name='type', default='awd') class AwodInstance(Instance): archive = models.FileField(upload_to='archives', name='archive') type = models.CharField(max_length=255, name='type', default='awod') class GithubInstance(Instance): archive = models.CharField(max_length=255) type = models.CharField(max_length=255, name='type', default='github') How can I get child model fields in django templates like user.instances.serverCode? Help me, please! Thanks in advance! -
Django Model: int() argument must be a string, a bytes-like object or a number, not 'tuple' [duplicate]
This question already has an answer here: Why does adding a trailing comma after a variable name make it a tuple? 6 answers My models.py: class Channel(models.Model): title = models.CharField(max_length=255) def snapshot_statistics(self): new_channel_stat = ChannelStatistic(channel=self) new_channel_stat.save() class ChannelStatistic(models.Model): channel = models.ForeignKey(Channel, on_delete=models.CASCADE) view_count = models.IntegerField(default=0) def save(self, *args, **kwargs): self.view_count = 3, super(ChannelStatistic, self).save(*args, **kwargs) when triggering snapshot_stastistics() i get the following error: int() argument must be a string, a bytes-like object or a number, not 'tuple' in the django debug i can see this: values [(<django.db.models.fields.related.ForeignKey: channel>, None, 35), (<django.db.models.fields.IntegerField: view_count>, None, (3,)), django treats my assignment of 3 to the view_count attribute a as tupel. Whats the matter of this behavior? How can i solve it? Thanks in advance! -
1366, Incorrect string value django or collate or tables in mysql.
When in django admin panel i try to add something in database using russian symbols - it gives me error: (1366, "Incorrect string value: '\\xD0\\xB2\\xD1\\x84\\xD1\\x8B' for column 'name' at row 1") Request Method: POST Request URL: https://giver.md/dev/admin/gift/categoryru/add/ Django Version: 1.10.4 Exception Type: OperationalError Exception Value: (1366, "Incorrect string value: '\\xD0\\xB2\\xD1\\x84\\xD1\\x8B' for column 'name' at row 1") Exception Location: /home/ubuntu/giver/server/local/lib/python2.7/site-packages/MySQLdb/connections.py in defaulterrorhandler, line 36 Python Executable: /home/ubuntu/giver/server/bin/python2 Python Version: 2.7.12 I know, that i need to change collation to resolve this problem? But how can i collate al tables in my mysql database using ubuntu 16? I tryed this, but this didn't helped me: SELECT CONCAT("ALTER TABLE ", TABLE_NAME," COLLATE utf8_general_ci") AS ExecuteTheString FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="giver" -
Using a controller to return different views in a django app
I want to return multiple views in my app according to the logic in a controller which is connected to the url resolver. Here is some example code of the idea that I have . class Project(Singleton): TYPE1, TYPE2 , TYPE3 = (0,1,2) def init(request,slug): self.pengine = ProjectEngine() self.pengine.init() self.request = request self.slug = slug ptype = pengine.getProjectType() return self.showProjectView(ptype) def showProjectView(self,projectType): if(projectType == TYPE1): return Type1View.as_view(self.request,self.slug) elif(projectType == TYPE2): return Type2View.as_view(self.request,self.slug) else: return Type3.as_view(self.request,self.slug) Type1View for example extends from Djangos default TemplateView class. ProjectEngine is supposed to be the model class to get the data from. The url resolver would then get the callable view from the init method, either using the Singleton idea that I have here, or using a class only method the same way as how a base View class is implemented. -
Importing module not working
I have a django (but i think it's nor revelant here) project where I try to add a script i did before. So I put it in a subdirectory of my project, and i have this structure (I know it's a little bit of a mess at the moment but it won't stay exactly like that) From views.py i want to import main.py (Especially the function excelToXml) . After searches on internet i found that code that i copied in views.py . If I undestood it right it add to the variable $PATH the directory parent of first_page and though, every subdirectory CURRENT = os.path.dirname(os.path.abspath(__file__)) PARENT = os.path.dirname(CURRENT) sys.path.append(PARENT) from ExcelToXML.main import excelToXml I also created a file __init.py__ in the directory ExcelToXML, this file is left empty. However even I did all that i still get this error when i run the django server File "c:\Users\CRA\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\bin\DevisVersOpen\DevisVersOpen\urls.py", line 18, in module from first_page import views File "c:\Users\CRA\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\django\bin\DevisVersOpen\first_page\views.py", line 13, in module from ExcelToXML.main import excelToXml ModuleNotFoundError: No module named 'ExcelToXML' I didn't find any solution that I could understand on internet so I really don't know how to solve this -
Django: how to properly structure a class having multiple of another class
I am learning Django and was wondering what the proper way is to structure the following situation: Let's say you have boxes containing 0 or more coloured balls (let's say there are 1000 colours). I understand how to structure the fact that a box contains balls, by making two classes and using the following code in the box class: balls = models.ManyToManyField(balls, blank=True) However, now I want to add how many of a certain coloured ball are in a given box. How should I go about this? -
Django error http method not allowed on a POST view
I have an error stating Method not Allowed (POST). But I have a Post method in my view. That's the only method that I have on my view. class AddOrRemoveFollower(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): #import ipdb; ipdb.set_trace() other_user = get_object_or_404(User, pk=kwargs['pk'] ) current_user = request.user if current_user is other_user: messages.success(request, 'You cannot follow yourself') return redirect(reverse('myfriendship:friends')) if current_user not in Follow.objects.followers(other_user): Follow.objects.add_follower(request.user, other_user) messages.success(request, 'You are now following a user') return redirect(reverse('myfriendship:friends')) else: Follow.objects.remove_follower(request.user, other_user) messages.success(request, 'You decided to unfollow this user') return redirect(reverse('myfriendship:friends')) urls.py url(r'^AddOrRemoveFollower/(?P<pk>\d+)/$', views.AddOrRemoveFollower.as_view(), name='AddOrRemoveFollower'), shell WARNING:django.request:Method Not Allowed (POST): /myfriendship/AddOrRemoveFollower/1/ WARNING:django.server:"POST /myfriendship/AddOrRemoveFollower/1/ HTTP/1.1" 405 0 html <form class="right" method="POST" action="{% url 'myfriendship:AddOrRemoveFollower' user.id %}"> {% csrf_token %} <input type="hidden" name="course_id" value="{{user.id}}"> <input class="btn btn-primary btn-sm red darken-2" type="submit" value="{% can_follow user request.user %}"> </form> -
How can I run both Django and PHP on the same domain (apache2) with mod_wsgi?
I would like to run Django and PHP in the same domain. Although there are some issues about this, I cannot make it run. When I run following code, the data in HTML code is just full code of php and php does not work. HTML (myproject/templates/test.html) <body> <form id="form_test"> <button type="button" onclick="exec_php()">Send</button> <script> function exec_php() { var formdata = new FormData($('#form_test').get(0)); $.ajax({ url: "../testphp", type: "POST", data: formdata, cache: false, contentType: false, processData: false, dataType: "text" }) .done(function (data, textStatus, jqXHR) { alert("data: " + data); }) .fail(function (jqXHR, textStatus, errorThrown) { alert("fail"); }); } </script> </form> </body> PHP (myprojcet/templates/test.php) <?php echo "php test" #this is a php test. I associated the url of ../testphp with myproject/templates/test.php in urls.py. I set /etc/apache2/sites-enabled/django.conf as follows. LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi-py35.cpython-35m-arm-linux-gnueabihf.so WSGIScriptAlias / /home/myproject/test/wsgi.py <Directory /home/myproject> Require all granted </Directory> <Directory /home/myproject/templates> Require all granted </Directory> Alias /static/ /home/myproject/static/ <Directory /home/myproject/static> Require all granted </Directory> HTML pages I set in urls.py is displayed, so I think I could set mod_wsgi correctly. But PHP does not work with mod_wsgi. PHP worked correctly when I put php files in documentroot and I used runserver. What should I do to work PHP with django on apache2 … -
Static Files Error - But my code seems correct?
I had a look a similar questions but couldn't seem to find the problem. I'm using Python with the Django framework as a backend. I'm trying to deploy my code to heroku and I get this error . "You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path." This is my code in settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'djreact/static'), ] This is the Github Repo just in case its useful! https://github.com/Hewlbern/ConsultingPage Thanks! -
Not able to use 'request' in django MultiTableMixin class
Am using django MultiTableMixin to list multiple tables in a page. I want to check user permissions from request and list table data, but am not able to get request in my class 'PersonTablesView'. The following is the sample code I got from a tutorial. from django_tables2 import MultiTableMixin from django.views.generic.base import TemplateView class PersonTablesView(MultiTableMixin, TemplateView): template_name = 'multiTable.html' tables = [ PersonTable(qs), PersonTable(qs, exclude=('country', )) ] table_pagination = { 'per_page': 10 } please help me to solve this. Thanks in advance.