Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /
So i was trying to make a simple Update Profile app But when i try to accesses the Update Page i have to Write the link Manually + the id in this case is 2 for example 'accounts/update/2' else it wouldn't work when i try to use "{% url 'edit_user' %}" i get this `NoReverseMatch at / Reverse for 'edit_user' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['accounts/update/(?P<pk>\\d+)/']` url.py url(r'^admin/', admin.site.urls), url(r'^$', main_views.home, name='home'), url(r'^uprofile$', main_views.uprofile, name='uprofile'), url(r'^accounts/update/(?P<pk>\d+)/', User_Profile_views.edit_user, name='edit_user'), url(r'^accounts/', include('allauth.urls')), 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', 'bio', 'phone', 'city', 'country', 'organization')) 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, "account/account_update.html", { "noodle": pk, "noodle_form": user_form, "formset": formset, }) else: raise PermissionDenied html form <div class="col … -
Can AUTH_USER_MODEL be set to a model that points back to User?
Can AUTH_USER_MODEL be set to a model that points back to User? I'm having trouble integrating an app into my project. My main app called 'Ponline' defined the following in its models.py: from django.contrib.auth.models import User from django.db import models class Student_User(models.Model): su_student = models.OneToOneField(User) su_user_phone = models.IntegerField(db_column='su_user_phone', default=0) su_user_bookmark = models.CharField(db_column='su_user_bookmark', max_length=50, default='') su_type = models.PositiveSmallIntegerField(db_column='su_type', default=0) su_access = models.TextField(db_column='su_access', default='') su_packs = models.TextField(db_column='su_packs', default='') def __unicode__(self): return str(self.su_student) I'm trying to integrate a pre-made app called 'Comm'. Comm has the following models.py: from django.db import models from django.conf import settings class UserQAProfile(models.Model): user = AutoOneToOneField(settings.AUTH_USER_MODEL, primary_key=True) points = models.IntegerField(default=0) def __str__(self): return self.user.username class Question(models.Model): slug = models.SlugField(max_length=200) title = models.CharField(max_length=200, blank=False) description = MarkdownField() pub_date = models.DateTimeField('date published', auto_now_add=True) views = models.IntegerField(default=0) user = models.ForeignKey(settings.AUTH_USER_MODEL) class Answer(models.Model): question = models.ForeignKey(Question) answer_text = MarkdownField() user = models.ForeignKey(settings.AUTH_USER_MODEL) class VoteParent(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) value = models.BooleanField(default=True) class Meta: abstract = True class AnswerVote(VoteParent): answer = models.ForeignKey(Answer) class Meta: unique_together = (('user', 'answer'),) This initally worked without setting anything for AUTH_USER_MODEL. But the apps' models weren't getting updated together and had independant login systems. So I decided to set it in my project's settings.py: AUTH_USER_MODEL = 'Ponline.Student_User' Please note here, … -
Problems with TabularInline in Django Admin
I'm porting an Access application to Python/Django. There is a SchoolInfo table and a Campuses table with a foreign key pointing to the SchoolInfo table. In Access, I have a Campuses subform (continuous) embedded into the SchoolInfo form with match fields defined properly pointing to School_ID. So for School 1 I only show campuses for that school. In Django, I added the SchoolInfo table to Admin and am trying to replicate the Access UI using TabularInline. Here are snippets of model and admin: class Schoolinfo(models.Model): school_id = models.AutoField(db_column='School_ID', primary_key=True) # Field name made lowercase. schoolid = models.CharField(db_column='SchoolID', max_length=10) # Field name made lowercase. schoolname = models.CharField(db_column='SchoolName', max_length=50, blank=True, null=True) # Field name made lowercase. class Campuses(models.Model): campus_id = models.AutoField(db_column='Campus_ID', primary_key=True) # Field name made lowercase. campusid = models.IntegerField(db_column='CampusID', default=1) # Field name made lowercase. schoolid = models.CharField(db_column='SchoolID', max_length=10) # Field name made lowercase. school = models.ForeignKey('Schoolinfo', models.DO_NOTHING, db_column='School_ID', unique=True) # Field name made lowercase.# school = models.IntegerField(db_column='School_ID') # Field name made lowercase. campusname = models.CharField(db_column='CampusName', max_length=15, blank=True, null=True) # Field name made lowercase. class CampusesInline(admin.TabularInline): model = Campuses admin.site.register(Campuses) class SchoolInfoAdmin(admin.ModelAdmin): fields = ( ('schoolid', 'schoolname'), ('contactname', 'contacttitle'), ('contactphone', 'contactemail'), ('clockhoursschool', 'schoolsendsawardletters'), ('tin_no', 'duns_no'), ('pell_id', 'ope_id')) save_on_top = True inlines … -
Gunicorn does not find main module with docker
I'm trying to set up django using docker following this tutorial but it fails with gunicorn not finding my main module. Folder structure: /project .env docker-compose.yml /web /static manage.py /django_project /apps_directories... /templates __init__.py settings.py wsgi.py Web section of docker-compose.yml web: restart: always build: ./web expose: - "8000" links: - postgres:postgres volumes: - ./web:/usr/src/app env_file: .env command: /usr/local/bin/gunicorn django_project.wsgi:application -w 2 -b :8000 Content of "django_project/wsgi.py": import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings") application = get_wsgi_application() Error thrown when starting container: [2016-11-01 16:39:48 +0000] [7] [INFO] Worker exiting (pid: 7) [2016-11-01 16:39:48 +0000] [1] [INFO] Shutting down: Master [2016-11-01 16:39:48 +0000] [1] [INFO] Reason: Worker failed to boot. [2016-11-01 16:39:49 +0000] [1] [INFO] Starting gunicorn 19.6.0 [2016-11-01 16:39:49 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2016-11-01 16:39:49 +0000] [1] [INFO] Using worker: sync [2016-11-01 16:39:49 +0000] [7] [INFO] Booting worker with pid: 7 [2016-11-01 16:39:49 +0000] [7] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.4/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/usr/local/lib/python3.4/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/local/lib/python3.4/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.4/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.4/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/local/lib/python3.4/site-packages/gunicorn/app/wsgiapp.py", line … -
django-extensions generating model graphs
django-extensions works well for me with Django1.8 but I have started a new project with Django1.9, Python 3.5 on Ubuntu 16.04 and trying to generate model graph but getting following errors: After installing django-extensions1.6 I run command to generate model graph: python manage.py graph_models -a -g -o myapp_models.png I get this error: CommandError: Neither pygraphviz nor pydot could be found to generate the image When I have installed pygraphviz I get this error: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/shaifali/.virtualenvs/drf-auth/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/shaifali/.virtualenvs/drf-auth/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/shaifali/.virtualenvs/drf-auth/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/shaifali/.virtualenvs/drf-auth/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/shaifali/.virtualenvs/drf-auth/lib/python3.5/site-packages/django_extensions/management/utils.py", line 57, in inner ret = func(self, *args, **kwargs) File "/home/shaifali/.virtualenvs/drf-auth/lib/python3.5/site-packages/django_extensions/management/commands/graph_models.py", line 89, in handle self.render_output_pydot(dotdata, **options) File "/home/shaifali/.virtualenvs/drf-auth/lib/python3.5/site-packages/django_extensions/management/commands/graph_models.py", line 152, in render_output_pydot graph.write(output_file, format=format) AttributeError: 'list' object has no attribute 'write' As mentioned django-extensions docs, when I try installing pyparsing==1.5.7 I get following error: Collecting pyparsing==1.5.7 Using cached pyparsing-1.5.7.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-1_hzke3p/pyparsing/setup.py", line 9, in <module> from pyparsing import __version__ as pyparsing_version File … -
Accessing created object in Django Rest Framework's ListCreateAPIView
I've been stuck with an old version of Django Rest Framework (2.x) for a while and I'm now upgrading for the latest 3.5.x I have the need to perform some post-processing of data on successful request and I was once able to do something like class ThingView(generics.ListCreateAPIView): """ Retrieve things and create a thing """ queryset = Thing.objects.all() serializer_class = ThingSerializer lookup_field = 'thing' def post(self, request, *args, **kwargs): res = super(ThingView, self).post(request, *args, **kwargs) if not is_successful_status(res): return res do_things_with(self.object) return res and I was then able to insert my logic in the normal DRF model workflow, in transaction or whatever. After the upgrade, unluckily, self.object is not bound anymore (surely due to the separation of concerns between Serializers and so on). So, while I can surely try to subclass ListCreateAPIView in some point and insert my logic there, I'd like to remain sticky as more as possible to the way the flow was created, so my question is: is there any sane way to access the just-created object in the post(3) method of a ListCreateAPIView? -
Celery doesn't autodiscover tasks from all apps
I have a problem with autodiscovery tasks from all y apps. For project proj |-- settings.py |-- app_tasks_found | |-- tasks.py | |-- app_cant_find_tasks | |-- tasks.py And following settings INSTALLED_APPS = [ 'proj.app_tasks_found', 'proj.app_cant_find_tasks', ] os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') from django.conf import settings app = Celery('proj') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) After I start celery worker celery worker -l info -A proj It shows me only tasks from app_tasks_found, but not from app_cant_find_tasks And of course celery raise error when I try to call task app_cant_find_tasks.tasks.test_task.delay() Celery can find tasks from app_cant_find_tasks if I explicitly set CELERY_IMPORTS = ("proj.app_cant_find_tasks.tasks",) These apps totally similar for me. I don't understand why celery can autodiscover tasks only from one app. Question is, where should I look at to fix my problem? -
How to get Custom List in a Viewset
How can we write a function in a ModelViewSet that get a list of distinct record in the database? Supposed that we have this model. class Animal(models.Model): this_id = models.CharField(max_length=25) name = models.CharField(max_length=25) species_type = models.CharField(max_length=25) ... and serializer class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ( 'this_id', 'name', 'species_type', ..., ) read_only_fields = ('id', 'created_at', 'updated_at') and ViewSet. class AnimalViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Animal.objects.all() serializer_class = AnimalSerializer I found this link useful such as decorators like @list_route() but i can't understand it well. I would like to get list of distinct Animal.species_type record from the ViewSet. Please help. -
ERR_INCOMPLETE_CHUNKED_ENCODING when the request body is not read
The following is an account of my issues with an interesting bug that though I've resolved, I don't understand. I found a solution, but I'm really hoping someone can provide some insight into the actual cause of the bug. Problem Background This issue first surfaced on the production server of our Django app. The stack was as follows AngularJS nginx uWSGI Django PostgreSQL Our team identified an issue with a single POST request on Safari. Safari would choke on the response and spit out an ERR_INCOMPLETE_CHUNKED_ENCODING. The post request was as follows: class ContractCloseOutSubmitView(APIView): def post(self, request, contract_id): contract = get_object_or_404( ContractCloseOut, pk=contract_id) if contract.submit(): return Response({"detail": "Closed successfully."}, status=200) else: raise ParseError("Could not submit.") The request is a simple request to mark an object as closed. We use this pattern in many places in the site, so this issue obviously required attention. Solution Our first clue was that the request did close the object. That is, the line if contract.submit() must have been reached. That narrows down the problem to the response. I did some reading and there is a wide range of causes for this error. We tried: Explicitly setting the content length in Django Some hacks that … -
Django mail backend for clients via an app
I'm trying to do something similar to Google Apps or Office 365 here. I'm currently using hostgator to maintain email accounts for my clients but will be shifting to AWS soon. Here's what I am trying to do: Create a mail server on myapp.com Create an email backend on myapp.com using Django to send & receive emails Clients can login via myapp.com/clientcompany to send / receive mails. Similarly a new client, say orangecompany.com is able to sign up by syncing their mx records (or similar ways ?) and later they can login to myapp.com/orangecompany to check send & receive email. I know this is going to be hard, but what I'm looking for is: 1. What kind of mail server do I setup for this. 2. Can Django alone do this, for managing databases, users, communication etc. 3. What would be the best way for me to start ? I will also definitely be willing to invest time and money, so please throw me your best suggestions and advice - DOs and DONTs or any pointers. Many thanks! -
django admin override queryset to get only last records in duplicates
Im trying to override a django admin model queryset so i can get only the last records in a list of duplicates. Already tried this two ways : class MyModelAdmin(admin.ModelAdmin): def get_queryset(self, obj): qs = super(MyModelAdmin, self).get_queryset(obj) return qs.order_by('process', '-modified_at').distinct('process') Or: class MyModelAdmin(admin.ModelAdmin): qs = super(ResponsibleStateFlowAdmin, self).get_queryset(obj) qs = qs.extra(where=[ "SELECT * FROM MyModel GROUP BY process ORDER BY modified DESC" ]) return qs But both throw errors....i tried distinct sintax for django and fails as well, and other post i've seen here are not exactly for what i need. Any idea ?, Thanks in advance ! -
how to synchronize module level functions in python
I am talking about simple function not class method. Is the functions in python are synchronize? Is there any way to maintain the synchronous? Is python give some built in tool to maintain synchronous state of a function? -
How to add a drop down list that pulls names from one table(model) and sets it as a field for another model?
I am trying to develop an attendance tracking system where i have made a "topic" model that has the fields related to the attendance of an employee. I have made a "topicform" that displays these fields as a form and once submitted, the details are stored in the "topic" table. I have another table called "staff" containing the names of the employees. I would like to edit the "name" field of my topic model to a choice field that shows all the employees from the staff table and inserts the selected option as the name field in the topic model. I am a beginner in Django web development and just need to add this functionality to make the whole system functional. Here is my code: models.py """ Definition of models. """ from django.db import models # Create your models here. SITES = ( ('Quincy','Quincy'), ('Bowling Green','Bowling Green') ) LEAVE_TYPE = ( ('Scheduled','Scheduled'), ('Unscheduled','Unscheduled') ) REASONS = ( ('Vacation','Vacation'), ('Sick','Sick'), ('Personal','Personal'), ('Work Comp','Work Comp'), ('Holiday Float','Holiday Float'), ('PBA','PBA'), ('Military Leave','Military Leave'), ('FMLA','FMLA'), ('No Call/No Show','No Call/No Show'), ('Bereavement','Bereavement'), ) ARRIVALS = ( ('Arrived Late','Arrived Late'), ('Left Early','Left Early'), ('Arrived Late & Left Early','Arrived Late & Left Early'), ) class Topic(models.Model): """A … -
crispy form to display in one line and not field under field
For some reason my crispy form is not displayed inline my template <div id="extra-content" > <form class="form-inline" action="" method="get" role="form"> {{lease.form|crispy}} <br> <button class="btn btn-secondary btn-sm" type="submit">Apply Filter</button> </form> </div> What could be wrong?Since in my form it does state inline. -
Simple Django Form Validation without Model
I'm trying to have inline validation appear in a Django form with a custom validator: def validate_true(value): if value != 'T': raise ValidationError('no', code='invalid') class Test2016(forms.Form): CHOICES_1 = [ ('T', True), ('F', False) ] q1 = forms.ChoiceField(choices=CHOICES_1, widget=forms.RadioSelect, label='1. Do you run or not?', help_text='', validators=[validate_true]) If they didn't select True, I want it to, right in the form, show that the answer is wrong when they click submit. This style validation but obviously with a True/Value radio select option instead. -
Django filter object with list of values
I have one field with ManyToManyField and want to filter my object with list of values.I get this values from dropdown. my template <form class="" action="." method="get"> <div class="SearchWithTags"> <select name="searchcategory" id="TagDropDown"> {% for k in types_list %} <option>{{k.name}}</option> {% endfor %} </select> <div class="PlaceForTags"> <div id="PlaceForTagsId" class="Tags"> </div> <a href="#"><img src="{% static 'assets/search.png' %}"></a> </div> </div> <input id="SendTagArray" type="submit" class="Search" name="startsearch" value="search"> </form> i'm creating array of this values values = []; $(function() { $('#TagDropDown').change(function() { values.push($('#TagDropDown option:selected').text()); $('#PlaceForTagsId').append("<div class='tagex'>" +$('#TagDropDown option:selected').text()+"</div>"); }); $("#SendTagArray").click(function(){ console.log(values); $.ajax({ type: 'GET', url: '/sitelink/', data: {'tags': values}, }); }); }); views.py tags = request.GET.getlist('tags', '') but i have problem that it doesn't send values to my view and tags variable is empty. -
celery 4.0.0 and Class based task workflow
Based on these examples: http://shulhi.com/class-based-celery-task/; https://blog.balthazar-rouberol.com/celery-best-practices http://shulhi.com/class-based-celery-task/ Class based Task in django celery I would like to create something similar: class CalculationWorker(Task): def __init__(self, id_user): self._id_user = id_user self._user = get_object_or_404(User, pk=self._id_user) # I need to understand if the bind work or if it's needed def _bind(self, app): return super(self.__class__, self).bind(celery_app) def _retrieve_some_task(self): # long calculation def _long_run_task(self): # long calculation self._retrieve_some_task() # Main entry def run(self): self._long_run_task() # def run_job(): worker = CalculationWorker(id_user=323232) task = worker.apply_async() The documentation seems to say it's possible (anyway it's not clear to me) http://docs.celeryproject.org/en/latest/userguide/tasks.html#custom-task-classes. It even says: """ This means that the init constructor will only be called once per process, and that the task class is semantically closer to an Actor. "" but http://docs.celeryproject.org/en/latest/whatsnew-4.0.html#the-task-base-class-no-longer-automatically-register-tasks explictly says: "The best practice is to use custom task classes only for overriding general behavior, and then using the task decorator to realize the task". As result I got a NotRegistered Exception due to this https://github.com/celery/celery/issues/3548, but adding app.tasks.register(CalculationWorker()) didn't solve it. I'm using Django 1.10.X and Celery 4.0.0 Is that approach still valid? Thanks -
Haystack django SearchQuerySet
I'm using Haystack Django for search engine. SearchQuerySet().filter(**conds) the conds may include : conds['name'] = Exact(name) conds['category'] = Exact(category) conds['city_id'] = Exact(city_id) but beside I also want to add list of sub_category as conditions, so is there any way to add something like conds['sub_category'] = list(city_id) -
conditions_leasetenant.tenant_id may not be NULL - USING django-ajax-selects
trying to use django-ajax-selects I want auto complete for tenant to work in my form and getting an error -conditions_leasetenant.tenant_id may not be NULL my form.py class LeaseTenantForm(forms.ModelForm): class Meta: model = LeaseTenant exclude = ['lease'] tenant = AutoCompleteSelectField('tenant', required=False, help_text=None) lookupchannel from ajax_select import register, LookupChannel from client.models import Tenant @register('tenant') class TenantLookup(LookupChannel): model = Tenant def get_query(self, q, request): return self.model.objects.filter(last_name=q) def format_item_display(self, item): return u"<span class='tag'>%s</span>" % item.last_name model class Tenant(CommonInfo): version = IntegerVersionField( ) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField(null=True, blank=True) phone = models.CharField(max_length=30) language = models.CharField(max_length=1, default='E', choices=LANGUAGE_CHOICES) external_address = models.CharField(max_length=90,null=True, blank=True) external_zip_code = models.CharField(max_length=50,null=True, blank=True) external_city = models.CharField(max_length=60,null=True, blank=True) external_state_province = models.CharField(max_length=30,null=True, blank=True) external_country = models.CharField(max_length=30,null=True, blank=True) status = models.CharField(max_length=1, default='N', choices=TENANT_STATUS_CHOICES,null=True, blank=True) class LeaseTenant(CommonInfo): version = IntegerVersionField( ) tenant = models.ForeignKey(Tenant) lease = models.ForeignKey(Lease) is_financialy_accountable = models.BooleanField(default=True) Traceback: File "C:\Users\I812624\dev\rentout\virtrentout\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\I812624\dev\rentout\rentout\conditions\views.py" in tenant_new 215. tenant.save() File "C:\Users\I812624\dev\rentout\virtrentout\lib\site-packages\django\db\models\base.py" in save 710. force_update=force_update, update_fields=update_fields) File "C:\Users\I812624\dev\rentout\virtrentout\lib\site-packages\django\db\models\base.py" in save_base 738. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\I812624\dev\rentout\virtrentout\lib\site-packages\django\db\models\base.py" in _save_table 822. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\I812624\dev\rentout\virtrentout\lib\site-packages\django\db\models\base.py" in _do_insert 861. using=using, raw=raw) File "C:\Users\I812624\dev\rentout\virtrentout\lib\site-packages\django\db\models\manager.py" in manager_method 127. return getattr(self.get_queryset(), … -
Django, what form field to use to get this result on the value attr of the field, Ex.: [(Id, Integer value from a select list)]
I have a view where I display one product (Bicycle) for rent. This product has a few attributes and one of them are the Extras. I would like to display a form called the BookingForm where my extras would be a field where I store all the extras related to this product and ask the client if he wants to add them to the basket. For this purpose a simple MultiChoiceField would do. The problem I'm facing is that I also need to know the quantity for this Extra, not only if the client wants it or not. So the end result I'm looking for its similar to this: class BookingForm(forms.Form): from_date = forms.DateTimeField(initial=datetime.datetime.now(), input_formats=['%d-%m-%Y %H:%M']) to_date = forms.DateTimeField(initial=datetime.datetime.now(), input_formats=['%d-%m-%Y %H:%M']) product = forms.IntegerField() quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) extras = forms.MultipleChoiceField( choices=list(), required=False, widget=forms.CheckboxSelectMultiple()) def __init__(self, *args, **kwargs): extras = ExtraData.objects.filter(product__pk=product, is_available=True) self.fields['extras'].choices = [(o.id, str(o.extra)) for o in extras.filter(is_accessory=False)] With this code I can get to know if the client wants or not the Extra, but I also want to know quantity. How can I add a Quantity select list to this field? The quantity field you see on this form is related to the product itself and sometimes … -
Nothing happens when I submit payment form using Django-paypal
I am developing a website with Django and I need a payment process. I decided to use django-paypal. So I followed these instructions : django-paypal documentation Here is my views.py : @login_required def buy_item(request): item = { "amt": "1.00", "inv": "inventory", # unique tracking variable paypal "cancelurl": "https://mywebsite.com/cancel_url/", # Express checkout cancel url "returnurl": "https://mywebsite.com/return_url/"} # Express checkout return url ppp = PayPalPro( item=item, # what you're selling payment_template="payment.html", # template name for payment confirm_template="confirmation.html", # template name for confirmation success_url="/success/", # redirect location after success nvp_handler=nvp_handler) return ppp(request) def nvp_handler(nvp): # This is passed a PayPalNVP object when payment succeeds. # This should do something useful! pass I also added the template files (payement.html and confirmation.html). I did also all settings configuration. The problem is that when I fill my form and submit it, nothing happens. The page is reloaded but nothing is done with the payment. Would someone know what am I doing wrong ? Is it better to use another package for payment processing with Django or someone has a successful code using this package ? Thanks ! -
page extension with tinyMCE django-cms
Hi everyone I create a page Extension using the documentation of Django CMS and work perfectly, Now I have a two text_area in my extension page, I want to include TinyMCE library to my text_area for this I have this in my models.py from django.db import models from cms.extensions import PageExtension from cms.extensions.extension_pool import extension_pool class IconExtension(PageExtension): image = models.ImageField(upload_to='icons', blank=True) description_short = models.TextField(blank=True, null=True, verbose_name="Short Description") description_large = models.TextField(blank=True, null=True, verbose_name="Large Description") extension_pool.register(IconExtension) and my admin.py have this from django.forms import * from django.db.models import * from django.contrib import admin from cms.extensions import PageExtensionAdmin from tinymce.widgets import TinyMCE from .models import IconExtension class IconExtensionForm(forms.ModelForm): some_field = forms.TextField(widget=TinyMCE(attrs={'cols': 80, 'rows': 10})) class Meta: model = IconExtension class IconExtensionAdmin(PageExtensionAdmin): form = IconExtensionForm admin.site.register(IconExtension, IconExtensionAdmin) right now I obtain this error 'module' object has no attribute 'ModelForm' but I have this include `from django.forms import *` any idea how to include tinyMCE in page extension, I am in the right way? -
New Relational Fields Added wont appear on DjangoRestFramework API
I have some issue here about the relational field (herd/herd_id) added to my model. it wont appear in the API as fields of my Animal model and AnimalSerializer djangorestframework Here is my Animal model and serializer: models.py class Animal(models.Model): this_id = models.CharField(max_length=25) name = models.CharField(max_length=25) species_type = models.CharField(max_length=25) breed = models.CharField(max_length=25) date_of_birth = models.DateField() birth_weight = models.IntegerField() sex = models.CharField(max_length=7) sibling_order = models.IntegerField() sire_id = models.CharField(max_length=20) sire_name = models.CharField(max_length=25) dam_id = models.CharField(max_length=25) dam_name = models.CharField(max_length=25) rf_id = models.CharField(max_length=25) comment = models.TextField(max_length=250, null=True) herd = models.ForeignKey(Herd, related_name='animals', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) class Meta: ordering = ('name',) serializers.py class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ( 'this_id', 'name', 'species_type', 'breed', 'date_of_birth', 'birth_weight', 'sibling_order', 'sex', 'sire_id', 'sire_name', 'dam_id', 'dam_name', 'rf_id', 'comment', 'herd_id', // <--- this field wont appear in the djangorestframework UI. 'created_at', 'updated_at', ) read_only_fields = ('id', 'created_at', 'updated_at') Here is the image. and look for the herd_id field it work appear. Please help -
Django allauth - facebook login doesn't work
I'm trying to set Facebook login and registration on my web page (localhost for now). Installed allauth Set settings.py Created an facebook app And now, when I click on http://127.0.0.1:8000/accounts/login/ facebook href, it returns this alert: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. According to sites, I've set domain name (in Django-admin Sites) to http://127.0.0.1:8000/ What should I do to make it work? -
Django AllAuth- Dynamic redirect URL
I've read multiple threads on SO and have dig deep into allauth source code as well, but was not able to set dynamic redirection_url after logging/signing up. So, my use-case is to redirect the user on the same page where he/she is presently at. I've a login form on every page(basically base.html), but it redirects everytime to the index page. This is what I've tried. 1) Adding hidden input field with name as next as mentioned here <form role="form" class="form-horizontal"> <fieldset> <div class="form-group signup_fb_wrapper"> <input type="hidden" name="next" value="/add_account_select/" /> <a class="btn wordwrapper btn-facebook btn-block" href="/accounts/facebook/login/?next={{request.path}}"> <span class="fa fa-facebook"></span> Signup with Facebook </a> </div> </fieldset> </form> Also, I've tried adding next as a query parameter in the href itself. but still no luck. 2) Over-ridding the Adapter class method get_login_redirect_url as mentioned here. class MyAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): return request.GET['next'] After logging in, I everytime get redirected to /. How can I changed the re-direction URL dynamically?