Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
serialize data to ArrayField(models.IntegerField(),default=list) field
I have the following field in postgres database :ArrayField(models.IntegerField(),default=list). When I send data from post request I get the following error: invalid literal for int() with base 10: '[176,68]' while the data sent is price:[176,68] Here is my serializer for price : class StringArrayField(ListField): """ String representation of an array field. """ def to_representation(self, obj): obj = super().to_representation( obj) # convert list to string return ",".join([(element) for element in obj]) def to_internal_value(self, data): return super().to_internal_value( data) class MySerializer(serializers.ModelSerializer): price = StringArrayField() class Meta: model = myModel fields =('price') -
Passing nested dict to Django model
Is it possible to pass a nested dict to Django model? I have passed single entry dicts before, such as: # create instance of model m = MyModel(**data_dict) m.save() But can I nest these entires within a dict to have them all processed vs. iterating through the dict and doing this one-by-one? -
Django Tests: User.authenticate fails
I've been stuck on this problem for a couple hours. I'm new to django and automated testing, and I've been playing around with Selenium and django's StaticLiveServerTestCase. I've been trying to test my login form (which works fine when I use runserver and test it myself, by the way.) Everything is working great, except I can't seem to successfully login my test user. I've narrowed down the break point to django's User.authenticate method. The User object is created successfully in my setUp and I can confirm that by accessing it's attributes in my test method. However, authenticate fails. I've looked at the following for help but they didn't get me very far: Django Unittests Client Login: fails in test suite, but not in Shell Authentication failed in Django test Any idea why authenticate fails? Do I need to add something to my settings? from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from django.contrib.auth.models import User from django.contrib.auth import authenticate class AccountTestCase(StaticLiveServerTestCase): def setUp(self): self.selenium = webdriver.Chrome() super().setUp() User.objects.create(username='test', email='test@test.com', password='Test1234', is_active=True) def tearDownClass(self): self.selenium.quit() super().tearDown() def test_register(self): user = authenticate(username='test', password='Test1234') if user is not None: # prints Backend login failed print("Backend login successful") else: print("Backend … -
Unsupported lookup 'level' for DateTimeField or join on the field not permitted
this is my view.py @list_route(methods=["post"]) def created_in_range(self, request): response = {} data = request.POST start = dateutil.parser.parse(data['start']) end = dateutil.parser.parse(data['end']) page_no = data['page_no'] tweets = Tweet.get_created_in_range(start, end, int(page_no)) serializer = TweetSerializer(tweets, many= True) response["data"] = serializer.data return Response(response, status= status.HTTP_200_OK) this is my class method of models.py @classmethod def get_created_in_range(cls, start, end, page_no): """ Returns all the tweets between start and end. """ tweets = cls.objects.filter(created_at__level__gte = start, created_at__level__lt=end ) paginator = Paginator(tweets, 5) return paginator.page(page_no) this is the error i get Internal Server Error: /api/twitter/created_in_range/ Traceback (most recent call last): File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/rest_framework/viewsets.py", line 95, in view return self.dispatch(request, *args, **kwargs) File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/rest_framework/views.py", line 494, in dispatch response = self.handle_exception(exc) File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/rest_framework/views.py", line 454, in handle_exception self.raise_uncaught_exception(exc) File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/rest_framework/views.py", line 491, in dispatch response = handler(request, *args, **kwargs) File "/home/kethan/Desktop/twitter_env/twitter_app/api/views.py", line 67, in created_in_range tweets = Tweet.get_created_in_range(start, end, int(page_no)) File "/home/kethan/Desktop/twitter_env/twitter_app/api/models.py", line 143, in get_created_in_range tweets = cls.objects.filter(created_at__level__gte = start, created_at__level__lt=end ) File "/home/kethan/Desktop/twitter_env/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, … -
Check if a record from one model exists in a list with records from another model in Django
I have two simple models defined in Django... one contains album names, and another one that links albums and users. class Album(models.Model): name = models.CharField(max_length=255) class UserAlbum category = models.ForeignKey(Album, on_delete=models.CASCADE) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) In my view I get the list of all albums, and I check which albums the user owns: albums = Album.objects.order_by('name') my_albums = UserAlbum.objects.filter(user_id=request.user.id) This all works well. However, I now need to display the list with albums online, and a little icon should appear if a user owns an album. I'm not sure how to do this. This is what I have: <ul> {% for info in albums %} <li>{{ info.name %} {% if SOME_CONDITION %} <span class="owner"></span>{% endif %}</li> {% endif %} I am not sure how to formulate SOME_CONDITION. It should basically say: if this album id is also in the my_albums list. But how can I do this? -
html table rowspan size limited?
I am creating a table by passing rowspan value from the backend. I write a piece of code for return {key: rowspan_value} dictionary. Here are some pictures. when it is unordered, the render like this: unordered render when it is ordered by the increase, the render like this: ordered by increase render when it is ordered by the decrease, the render like ordered by decrease render For my purpose, all those elements should align with the most left column. The code for table goes like this: <div id="predict_list" class="box span9"> <div class="search form-inline"></div > <div class="table-style"> <table class="table table-striped table-bordered"> <thead style="background-color:#B0C4DE; font-size: 13px;" > <tr> <th style="text-align: center;min-width: 70px; vertical-align: middle">&nbsp</th> <th style="text-align: center;min-width: 70px; vertical-align: middle">物资名称</th> <th style="text-align: center;min-width: 70px; vertical-align: middle">计划用量</th> </tr> </thead> {% load temp_extras %} {% for k, v in sorted_count_per_type.items %} <tr> <th style="text-align: center; min-width: 70px; vertical-align: middle" rowspan="{{ v }}">{{ k }}</th> </tr> {% endfor %} </table> </div> </div> Please help me to solve this problem, This is alread 4.30am in china. -
Initiating a scrapy crawl as a Django management command
I’ve got a project that connects Django and Scrapy where I’m looking to initiate a spider crawl through a Django management command. The idea is to run it periodically via cron. I’m using Django 1.11, Python 3 and Scrapy 1.5 This is what the code for my custom management command ‘~/djangoscrapy/src/app/management/commands/run_sp.py’ file looks like from django.core.management.base import BaseCommand from scrapy.cmdline import execute import os from django.conf import settings os.chdir(settings.CRAWLER_PATH) class Command(BaseCommand): def run_from_argv(self, argv): print ('In run_from_argv') self._argv = argv[:] return self.execute() def handle(self, *args, **options): execute(self._argv[1:]) When I run $python manage.py run_sp crawl usc I get this error…. In run_from_argv Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/greendot/lib/python2.7/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/greendot/lib/python2.7/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/greendot/webapps/scraper3/src/app/management/commands/run_sp.py", line 15, in run_from_argv return self.execute() File "/home/greendot/lib/python2.7/django/core/management/base.py", line 314, in execute if options['no_color']: Here is my project structure SRC ├── app │ ├── __init__.py │ ├── admin.py │ ├── management │ │ └── commands │ │ ├── __init__.py │ │ ├── run_sp.py │ ├── models.py │ └── views.py ├── example_bot │ ├── dbs │ ├── example_bot │ │ ├── __init__.py │ │ ├── items.py │ │ ├── middlewares.py │ │ … -
~/.aws/credentials setup and boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request
i have to set up this credentials ~/.aws/credentials in my django projet but i don't know what is this first time i seen it please tell me where and how i have to add this in my django project. i want to setup this because i am getting this error (boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request) in py django project when i am running "python manage.py collectstatic" command and my reasion is mumbai. i uploaded my website on heroku but that not showing images so i am trying to serve it using aws s3 but due to this error message i am not able to move further many people recommend to setup this " ~/.aws/credentials" so please tell me in detail what i have to do ? -
Role based Authorization Django/Graphql/Apollo/Vue
I am working on a project that uses Django as the backend with graphql/graphene as an api and Vue Js and apollo client for the front end. I am lost as to how I can implement role based authorization using this set up. I am wondering if a can using Django's base auth package or can I get DRF authorization to work with this? I know that graphene has support for authorization using relay, can I make this work with apollo in the front end? Or is a better idea to use some package such as vue-kindergarden to keep all the authorization in the vue js front end? Keeping all the authorization seems somewhat sketchy to me. Has anyone had an experience with this or have some input on what the best option is? -
Q: Django crispy forms - change behavior depending url
I don't know how to implement this with django crispy forms. I have an interface with a URL like this: myurl.com/movements/new And I have a select in the form with the type of movement. When there is not a type of movement explicitly assigned, just shows the select without any option selected. When user access to form with an URL like myurl.com/movements/income/ I want this select to have by default the income option. And so on with every possible option. I know that I can use JavaScript for this, but I think that it would be better to have it on the back-end. How can I achieve this on the back-end part? -
django post_save signal is getting triggered twice when I try to save the instance, it is actually triggering the update part
I have two models Invoce and Payin. Invoice can be payed in multiple payins. While updating Invoice details with post_save signal. after create logic is executed I attach an Invoice Id to the Payin instance and save it. This save is triggering the signal again(as it's supposed to be) this time update logic i.e in the else part of if create: is executed there by one payin is added twice to the paid amount in invoice. How can I avoid the Update logic when I save instance in the signal logic. class Invoice(BaseEntity): """ Invoices are generated based on events state""" STATUS_CHOICES=( ('CREATED', 'Created'), ('CONFIRMED', 'Confirmed'), ('PARTIAL_PAYMENT', 'Partially Paid'), ('RECEIVED', 'Received'), ('CLOSED', 'Closed') ) customer = models.ForeignKey( Customer, related_name='invoices', ) event = models.ForeignKey( 'booking.Event', related_name='invoice', ) generated_date = models.DateField( verbose_name='date invoice generated' ) due_date = models.DateField( verbose_name='date payment is expected' ) status = models.CharField( max_length =15, choices = STATUS_CHOICES, default = 'CREATED', ) amount = models.IntegerField( default=500, validators=[ MinValueValidator( 10, message = 'Amount should be greater than 10' ), MaxValueValidator( 10000000, message = 'Amount should be less than 10000000' ), ] ) paid = models.IntegerField( default=500, validators=[ MinValueValidator( 10, message = 'Amount should be greater than 10' ), MaxValueValidator( 10000000, … -
django - restricting user access to related models
In my project, I have a Bot model that has a Foreign key to a User model. Each user should manage his own Bot instances, so in my BotListView, BotUpdateView, BotCreateView etc. I check if the user owns the object/object list, which is fairly trivial. However, Bot has a lot of dependent models: ContentBlocks, Campaigns, Subscribers, Questions etc., all of which have FKs to Bot. These dependent models in turn have their own dependent models, e.g. Campaign has CampaignDeliverys, Subscriber has Tickets etc. And for all of those I need access control. So in all my views I have to go three or four FK's up the relations to find the particular Bot to check the object user. It looks like so: if delivery.campaign.bot.user == request.user if answer.question.bot.user == request.user if renewal.ticket.subscriber.bot.user == request user ... you get the idea. I need a simpler way than this. I thought of assigning an FK to User to each and every one of my model to simplify the owner lookup, but this will be even less manageable than now. Also, storing FKs to User in millions of CampaignDelivery rows is a huge overhead. There's also a way to define an owner() method … -
Error getting users from group django
Now I'm working on a system for filing applications for repairing equipment in one organization. Each application can be owned by a certain person from the group (Which is set in the admin panel) of technical support. The model of the application is partially written, but I can not figure out the purpose of the application for this application. models.py class Owner(models.Model): OWNER_CHOICES = [] for user in User.objects.filter(name = 'Техническая поддержка'): if user.has_perm('helpdesk.can_close'): OWNER_CHOICES.append(user) name = models.CharField(max_length=50, choices=OWNER_CHOICES) def __str__(self): return self.name class Application(models.Model): STATUS_CHOICES = ( ('in_the_work', 'В работе'), ('new', 'Новая'), ('completed', 'Завершена') ) authors = models.ForeignKey('auth.User') title = models.CharField(max_length=50) text = models.TextField() room = models.CharField(max_length = 4) published_date = models.DateField(blank=True, null=True, default = datetime.datetime.now) status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='new') owner = models.ManyToManyField(Owner) class Meta: permissions = ( ("can_add_change", "Добавлять и изменять"), ("can_close", "Закрывать"), ("can_assign", "Назначать"), ) def publish(self): self.publish_date = datetime.datetime.now() self.save() def __str__(self): return self.title What am I doing wrong? Maybe you have some advice? If I do so, class Owner(models.Model): OWNER_CHOICES = [] for user in Group.objects.filter(name = 'Техническая поддержка'): #if user.has_perm('helpdesk.can_close'): OWNER_CHOICES.append(user) name = models.CharField(max_length=50, choices=OWNER_CHOICES) def __str__(self): return self.name Then there is a migration error SystemCheckError: System check identified some issues: ERRORS: <class … -
Django's model.save() is not working and no error is shown
this is my models.py file from django.db import models, connection from django.conf import settings as django_settings from datetime import datetime, timedelta from email.utils import parsedate from django.utils import timezone import os import socket from twitter_app import settings current_timezone = timezone.get_current_timezone() def parse_datetime(string): if settings.USE_TZ: return datetime(*(parsedate(string)[:6]), tzinfo=current_timezone) else: return datetime(*(parsedate(string)[:6])) class Tweet(models.Model): # Basic tweet info tweet_id = models.BigIntegerField() text = models.CharField(max_length=250) truncated = models.BooleanField(default=False) lang = models.CharField(max_length=9, null=True, blank=True, default=None) # Basic user info user_id = models.BigIntegerField() user_screen_name = models.CharField(max_length=50) user_name = models.CharField(max_length=150) user_verified = models.BooleanField(default=False) # Timing parameters created_at = models.DateTimeField(db_index=True) # should be UTC user_utc_offset = models.IntegerField(null=True, blank=True, default=None) user_time_zone = models.CharField(max_length=150, null=True, blank=True, default=None) # none, low, or medium filter_level = models.CharField(max_length=6, null=True, blank=True, default=None) # Geo parameters latitude = models.FloatField(null=True, blank=True, default=None) longitude = models.FloatField(null=True, blank=True, default=None) user_geo_enabled = models.BooleanField(default=False) user_location = models.CharField(max_length=150, null=True, blank=True, default=None) # Engagement - not likely to be very useful for streamed tweets but whatever favorite_count = models.PositiveIntegerField(null=True, blank=True) retweet_count = models.PositiveIntegerField(null=True, blank=True) user_followers_count = models.PositiveIntegerField(null=True, blank=True) user_friends_count = models.PositiveIntegerField(null=True, blank=True) # Relation to other tweets in_reply_to_status_id = models.BigIntegerField(null=True, blank=True, default=None) retweeted_status_id = models.BigIntegerField(null=True, blank=True, default=None) @property def is_retweet(self): return self.retweeted_status_id is not None @classmethod def create_from_json(cls, raw): """ Given … -
How can i convert this php code to django code? [on hold]
How can i convert this php code to django code? Here is the link: Php code! Thanks for your help... -
django rest reverse field serializer validation issue
I would like to serialize the email addresses of the user. Email address is a reverse relation field, and comes from a third party module, so I can't set a related name. Still, I would like to expose it as 'email_addresses'. Solution works for reading, but during update validation error is raised: 'email address with this e-mail address already exists.' There is a single email in the system, so it's obviously not the real problem. The error is raised by UniqueValidator, which should ignore the current instance of course. But instance is not set, so it never passes validation. Seems to me that serializer does not know about the reverse relation, although I set it by the source parameter. I have these models and serializers: # from allauth.account.models class EmailAddress(models.Model): user = models.ForeignKey(allauth_app_settings.USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE) email = models.EmailField(unique=app_settings.UNIQUE_EMAIL, max_length=app_settings.EMAIL_MAX_LENGTH, verbose_name=_('e-mail address')) ... # our user implementation class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, verbose_name=_('Email address')) ... @property def email_addresses(self): return EmailAddress.objects.filter(user=self) class EmailAddressSerializer(serializers.ModelSerializer): class Meta: model = EmailAddress # from allauth.account.models fields = ('email', 'verified', 'primary') class UserSerializer(serializers.ModelSerializer): email_addresses = EmailAddressSerializer(many=True, source='emailaddress_set') .... class Meta: model = User fields = ('email', 'first_name', 'last_name', 'email_addresses') def update(self, instance, validated_data): # does not … -
Django > Image does not work in HTML
I began to study the framework of Django. Im need shows the image profile, but image is not displayed and the console does not display an error. In the browser inspector is show this way: img scr="/media/users/images.jpeg" How to display an image in HTML? settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='users', blank=True, null=True) html <div> <img scr="{{ avatar.url }}"> </div> -
How to connect to vmware web server from windows?
I have created a Django web server on VMWare (Ubuntu Server OS, Bridged Network, IP 192.168.1.7) and I can SSH to it from Windows PC (host computer). My web server already run at http://127.0.0.1:8080/. February 24, 2018 - 16:58:55 Django version 2.0.2, using settings 'fortress_of_mobile_phone.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CONTROL-C. But when I tried to connect to this web server from Windows PC then I got the following error: This site can’t be reached 192.168.1.7 refused to connect. Could you please take some time help me to fix it. Thank you. -
No show input autocomplete in django-autocomplete-light
I am trying to autocomplete a foreign key field: I'm trying to autocomplete a foreign key field, but I can not do it and I'm following the steps in the documentation View class ProductoAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Producto.objects.all() if self.q: qs = qs.filter(nombre__icontains=self.q) return qs Url url(r'^producto-autocomplete/$',ProductoAutocomplete.as_view(),name='producto-autocomplete',), and the result is correct: Result in image Forms class DetalleForm(forms.ModelForm): class Meta: model = DetalleVenta fields = [ 'producto', 'cantidad', 'preciounit', 'subtotal', ] labels = { 'producto':'Producto', 'cantidad':'Cantidad', 'preciounit':'Prec.Unit.', 'subtotal':'Subtotal', } widgets = { 'producto':forms.Select(attrs={'class':'form-control', 'autofocus':True}), 'producto': autocomplete.ModelSelect2(url='producto-autocomplete', attrs={'data-placeholder': 'Royal ...', 'data-minimum-input-length': 2}), 'cantidad':forms.NumberInput(attrs={'class':'form-control cantidad'}), 'preciounit':forms.NumberInput(attrs={'class':'form-control'}), 'subtotal':forms.NumberInput(attrs={'class':'form-control subtotal', 'readonly':True}), } DetalleFormSet = inlineformset_factory(Venta, DetalleVenta, form=DetalleForm, extra=1) Template: {% extends 'base/base.html' %} {% load static %} {% block titulo%} Registrar venta {%endblock%} {% block contenido %} <div class="col-md-12"> <form method="post">{% csrf_token %} <div class="col-md-4 form-group"> <label class="font-weight-bold" for="{{form.cliente.name}}">{{form.cliente.label}}</label> {{form.cliente}} </div> <h4 class="text-left">Detalle de venta: </h4> <div class="table-responsive-sm"> <table class="table" id="tablaDetalle"> {{ detalleformset.management_form }} <thead class="thead-dark"> <th>Producto</th> <th width="100px">Cantidad</th> <th width="115px">Prec.Unit.</th> <th width="115px">Subtotal</th> <th>Acción</th> </thead> <tbody> {% for form in detalleformset.forms %} <tr class="formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} … -
What's wrong with django queryset? I get different answer when access the same indice
I found that the objects could be duplicate in a queryset. However, when I try to access each of the object and do nothing, it changes and seems to be right. Here are the commands I have typed into the shell -
django channels async process
I am still pretty new to django-channels and directly starting with channels 2.0 so diverse examples are still a bit hard to find yet. I am trying to understand how can I create an asynchronous process in a channel and make a js client listen to it? while connecting to my consumer, I am checking for a running stream on a thread and try to send back predictions on the channel. This process is asynchronous but I am not sure how to properly use an AsyncConsumer or AsyncJsonWebsocketConsumer. so far I have a simple consumer like this: consumers.py import threading from sklearn.externals import joblib from channels.generic.websocket import JsonWebsocketConsumer from .views import readStream class My_Consumer(JsonWebsocketConsumer): groups = ["broadcast"] the_thread_name = 'TestThread' def connect(self): the_thread = None self.accept() # check if there is an active stream on a thread for thread in threading.enumerate(): if thread.name == self.the_thread_name: the_thread = thread break if the_thread == None: xsLog.infoLog('No Stream found yet...') self.close() else: the_stream = readStream() #... the_estimator = joblib.load('some_file','r') the_array = np.zeros(shape=(1,93), dtype=float) self.predict(the_thread,the_stream,the_array,the_estimator) def disconnect(self,close_code): pass async def predict(self,the_thread,the_stream,the_array,the_estimator): while the_thread.isAlive(): sample = await the_stream.read() if sample != [0.0,0.0,0.0] and 'nan' not in str(sample): the_array = np.roll(self.the_array,-3) the_array[0][-3] = sample[0] the_array[0][-2] = … -
Elasticsearch TransportError(400, 'search_phase_execution_exception', 'No mapping found for [name.raw] in order to sort on')
Being a newbie with Elasticsearch, I want to implement it into my project using django-elasticsearch-dsl-drf. I got this error whenever I tried to run an Elasticsearch query : RequestError at /search/authors/ TransportError(400, 'search_phase_execution_exception', 'No mapping found for [name.raw] in order to sort on') I don't know why, Here is the document mapping for authors : from django.conf import settings from django_elasticsearch_dsl import DocType, Index, fields from django_elasticsearch_dsl_drf.compat import KeywordField, StringField from books.models import Author __all__ = ('AuthorDocument',) INDEX = Index(settings.ELASTICSEARCH_INDEX_NAMES[__name__]) # See Elasticsearch Indices API reference for available settings INDEX.settings( number_of_shards=1, number_of_replicas=1 ) @INDEX.doc_type class AuthorDocument(DocType): """Author Elasticsearch document.""" id = fields.IntegerField(attr='id') name = StringField( fields={ 'raw': KeywordField(), 'suggest': fields.CompletionField(), } ) salutation = StringField( fields={ 'raw': KeywordField(), 'suggest': fields.CompletionField(), } ) email = StringField( fields={ 'raw': KeywordField(), } ) birth_date = fields.DateField() biography = StringField() phone_number = StringField() website = StringField() headshot = StringField(attr='headshot_indexing') class Meta(object): """Meta options.""" model = Author # The model associate with this DocType I don't know why I have this error. Please help! -
Link on admin model change page (Django 2.0)
I want to add a link on the admin change page, pointing the user to another page with more dynamic content (own view). In the list view it worked well. I added a callable to the model like so: class MyModel(MPTTModel): name = models.CharField(max_length=50, unique=False) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) # ... # things omitted for brevity # ... def link_further(self): url = reverse('myapp:further_page', kwargs={ 'page_id': str(self.id) }) return format_html( '<a href="' + url + '" target="_blank">Click here to show the {} page.</a>', self.name, ) class MPTTMeta: order_insertion_by = ['name'] As you can see, I use django-mptt. After reading the code, I cannot imagine that the fact that I cannot get it to show is related to django-mptt. MPTTModel usses the six library to create a meta class from MPTTModelBase and models.Model (https://github.com/django-mptt/django-mptt/blob/master/mptt/models.py#L401). In django there seem to be many and one places where the fields can be defined. To avoid having it overwritten in some miraculas way (feel free to let me know where this should be done), I tried putting it into the call to admin.site.register admin.site.register( MyModel, MyMPTTModelAdmin, fields = ('link_further', '...'), # things omitted for brevity ) Which resulted in a FieldError. After … -
python selenium in html select value option
i have this html form using django framework : <form action="" method="POST">{% csrf_token %} <select name="index" class="form-control"> {% for post in posts %} <option value="{{ post.name }}"</option> {% endfor %} </select> <input class="btn" type="submit"> </form> and i want to test it using selenium but how to can use selenium to test this html form ? i am confused at <option value="{{ post.name }}"</option> because this is dynamic. some help ? -
Django raises a page not found for all forms on shared hosting
This is my first time posting here and so, I am sorry if I am doing something wrong. So, I am a beginner in the world of hosting and web development with django. I have built a basic website and tried hosting it via shared hosting on a2hosting. There seemed to be some problems with FastCGI and they suggested to use django as a wsgi application. This was done by first, creating a virtualenv using the cpanel's setup python. Then, installing django and, using passenger, to run the project. The basic website that I created works no problem on my system. However, on the server, it seems to be having problems with pages leading from a form. (For example, it allows me to get to the django's admin site but says page not found once I try to login). So, I experimented a bit and soon realized something: I have a form with "action" url leading to something like this, examplewebsite.com/new_book. Once the form is filled and submitted, it should submit to this url. And then, it should redirect to, examplewebsite.com/books. However, the request is being made to, examplewebsite.com/new_book/books. The view function has: HttpResponseRedirect(reverse('namespace:name')) I tried removing the reverse bit …