Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to Render Bundle (404) - React with Jango
I've been stuck for a while in this part to render a simple, basic HTML page with a react container. What happens is that the system is unable to find the bundle, popping out the following error in the browser - element inspection: main-e81ebca393352343ecd4.js Failed to load resource: the server responded with a status of 404 (NOT FOUND) While popping the following error in the "python manage.py runserver" terminal window: [29/Aug/2017 16:40:57] "GET / HTTP/1.1" 200 269 [29/Aug/2017 16:40:57] "GET /static/bundles/main-e81ebca393352343ecd4.js HTTP/1.1" 404 1721 Now I've been through multiple times my settings.py file and my webpackconfig.js file, however, I havent been able to find where is my mistake so far. webpack.config.js: //require our dependencies var path = require('path') var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { //the base directory (absolute path) for resolving the entry option context: __dirname, //the entry point we created earlier. Note that './' means //your current directory. You don't have to specify the extension now, //because you will specify extensions later in the `resolve` section entry: './assets/js/index', output: { //where you want your compiled bundle to be stored path: path.resolve('./assets/bundles/'), //naming convention webpack should use for your files filename: '[name]-[hash].js', }, plugins: [ β¦ -
Can this be done with Scrapy or something else?
Compared to 99% of you on this site, I am a newbie when it comes to programming & other technical issues. Luckily I have a son with a CS degree who is pretty talented. Unfortunately, he is extremely busy so when I ask him to do something for me I have to have my ducks in a row to make him efficient. Scrapy looks like a tool that he could use to do something for me. I just wanted this communitiesβ thoughts on whether Iβm sending him in the right direction. I promise that there will be no newbie level follow-up questions from me once I have determined that this is the right tool for him to use for what I want to accomplish. Iβm looking for a tool that can constantly and quickly scan part of a website for newly added pages. Ideally, I need it to find the new page within 1-2 seconds after it is added. Before normally using this website I am required to logon to gain access (so it needs to be able to handle that). I only want this tool to scan the part of the website where the web address starts with an β¦ -
how to catch the unauthenticated response 401 from django rest api in react native
Here in views.py class StockList(APIView): #authentication_classes = (TokenAuthentication,) permission_classes = [IsAuthenticated] def get(self,request): stocks = Stock.objects.all() serializer = StockSerializer(stocks,many=True) return Response({'user': serializer.data,'post': serializer.data}) def post(self): pass Here if token is not valid then it doesnt send any data.. so in react native I have to patch that error and show their invalid credentials. So here is my react.js file componentDidMount() { return fetch('http://10.42.0.1:8000/stocks/', { method: "GET", headers: { 'Authorization': `JWT ${"eyJhbGciOiIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNhbSIsInVzZXJfaWQiOjYxLCJlbWFpbCI6IiIsImV4cCI6MTUwNDAxNTg4M30.o_NjgPNsxnLU6erGj5Tonap3FQFxN3Hh_SsU6IvLO9k"}` } }) .then((response) => response.json()) .then((responseData) => { console.log(responseData.detail); let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ isLoading: false, sa: ds.cloneWithRows(responseData.post), }, function() { }); }) .catch((error) => { console.error(error); }); } here if json data is not provided then show some error.. how could I accopmlished that. thank you. -
How can I display error messages in django
As I can put an error message to the user when it completes the fields of my form, I am using views based on classes CreateView .. and I only found success_message class RegistroUsuario(CreateView): model = User template_name = "usuario/registrar.html" form_class = RegistroForm success_url = reverse_lazy('denuncias:index') permission_denied_message = "You must login to contact the administrator" I also tried to add this function but it no longer creates the regitros when I use it def form_invalid(self, form): response = super(RegistroUsuario, self).form_invalid(form) messages.error( self.request, 'Error de validacion: Email o contraseΓ±as incorrectas, recuerde las contraseΓ±as deben tener un minimo de 8 caracteres con letras y numeros') return response -
Error 'str' object has no attribute 'resolve_expression when using CASE WHEN statement in Django
Perhaps there is a better way to doing it, but I am trying to count the number of members by age group. It is the first time I am trying to use CASE/WHEN and I am running into the above error. This is the case statement I am using: Case( When(2017 - birthdate__year__range=(0,10), then=Value('0,10')), When(2017 - birthdate__year__range=(11,20), then=Value('11,20')), When(2017 - birthdate__year__range=(21,30), then=Value('21,30')), When(2017 - birthdate__year__range=(31,40), then=Value('31,40')), When(2017 - birthdate__year__range=(41,50), then=Value('41,50')), When(2017 - birthdate__year__range=(51,60), then=Value('51,60')), When(2017 - birthdate__year__range=(61,70), then=Value('61,70')), When(2017 - birthdate__year__range=(71,80), then=Value('71,80')), When(2017 - birthdate__year__range=(81,90), then=Value('81,90')), When(2017 - birthdate__year__range=(91,100), then=Value('91,100')), When(2017 - birthdate__year__gt=100, then=Value('100+')), output_field=CharField(), ) My query is: members=MK.objects.filter(**filters).annotate(age_groups= Case( When(2017 - birthdate__year__range=(0,10), then=Value('0,10')), When(2017 - birthdate__year__range=(11,20), then=Value('11,20')), When(2017 - birthdate__year__range=(21,30), then=Value('21,30')), When(2017 - birthdate__year__range=(31,40), then=Value('31,40')), When(2017 - birthdate__year__range=(41,50), then=Value('41,50')), When(2017 - birthdate__year__range=(51,60), then=Value('51,60')), When(2017 - birthdate__year__range=(61,70), then=Value('61,70')), When(2017 - birthdate__year__range=(71,80), then=Value('71,80')), When(2017 - birthdate__year__range=(81,90), then=Value('81,90')), When(2017 - birthdate__year__range=(91,100), then=Value('91,100')), When(2017 - birthdate__year__gt=100, then=Value('100+')), output_field=CharField(), )).values('age_groups',).annotate(total=Count('age_groups')) I read to use models.CharField() for output field but still it didn't make a difference. Is my approach at right? -
Django ModelForm error message not showing in template
I have created some custom error message following the documentation (as best as I can find) but I'm not getting any errors, let alone my custom errors. Here's my code: forms.py class UploadFileForm(forms.ModelForm): class Meta: model = Job fields = ['jobID','original_file'] labels = { 'jobID': _('Job ID'), 'original_file': _('File'), } error_messages = { 'jobID': { 'max_length': _("Job ID is limited to 50 characters."), 'required': _("Please provide a Job ID."), 'invalid': _("Job ID must be a combination of letters, numbers, - and _.") }, 'original_file': { 'required': _("Please provide a file."), 'validators': _("Please ensure you are selecting a zipped (.zip) GDB."), }, } help_texts = { 'original_file': _('Please provide a zipped (.zip) GDB.'), } upload.html <form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data" name="uploadForm"> {% csrf_token %} {% for field in form %} <div> <strong>{{ field.error }}</strong> {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class ="help-text">{{ field.help_text }}</p> {% endif %} </div> {% endfor %} <br /> <button type="button" id="uploadButton" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off" style="margin: auto 20%; ">Upload</button> </form> I've included everything I think is relevant, let me know if you need anything more. -
django error " NoReverseMatch at /polls/"
l am following a tutorial and l have been getting these errors!why? i need your help. on the error page it says "NoReverseMatch at /polls/ Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls/$(?P[0-9]+)/$']" please help, l am struggling through this tutorial. the tutorials link"https://docs.djangoproject.com/en/1.11/intro/tutorial04/" my index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li> <a href="{% url 'polls:detail' question.id %}">{{question.question_text}}</a></li> {% endfor %} </ul> {% else %} <p> No polls are available </p> {% endif %} urls.py in polls app from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] my views.py in polls app from django.template import loader from django.http import HttpResponse from .models import Question from django.shortcuts import get_object_or_404, render from django.urls import reverse # Create your views here. def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404 (Question,pk=question_id) return render(request, 'polls/detail.html' , {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls:results', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, β¦ -
Setting up a virtual environment for python3 using virtualenv on Ubuntu
I want to learn Django so for that, as per the instructions on the website, you need to create a virtual environment. I've heard enough horror stories about people corrupting their OS cause they didn't set up the virtual environments properly so it's safe to say I'm sufficiently paranoid. I've created a separate folder/directory VirtualE at located at Academics/CS/VirtualENV and I want to create all my virtual environments there. As per the website, the following command should be used - virtualenv --python=`which python3` ~/.virtualenvs/djangodev I'm not sure what exactly I should write in place of the single quotes (the which python3 part). I wrote the following - virtualenv --python=3.5.2 ~/Academics/CS/VirtualENV/DjangoDev It says The path 3.5.2 (from --python=3.5.2) does not exist Where exactly am I going wrong? -
elasticsearch (Python/Django) bulk indexing throws No Index error
I am using elasticsearch's python client and elasticsearch-dsl as well. I have created an index IndexName and I validated the existence of the index. I have a doc_type DocumentModelIndex associated with this IndexName. def bulk_indexing(): from app.models import DocumentModel DocumentModelIndex.init(index=settings.ES_INDEX) es = Elasticsearch() bulk(client=es,actions=(b.indexing() for b in DocumentModel.objects.all().iterator())) When I run the above code I get the following error: ValidationException: No index. I tried Putting a document into that index using: curl -XPOST "http://localhost:9200/index_name/document_model_index/" -d "{\"source\":\"google\"}" and this worked. I am new to elasticsearch and am not able to figure this out. Any help would be much appreciated! -
geodjango query format coordinates- convert lat lon , open street map
I have a polygon in my model citys but in my map for example bogota has the coordinate -8243997.66798 , 517864.86656 -> open street maps; but i need make query with coordinates like (4.697857, -74.144554) -> google maps. pnt = 'POINT(%d %d)'%(lon, lat) zonas = ciudad.zona_set.filter(polygon__contains=pnt) zonas is empty :/ , how i can convert lat and lon to standar coordinates in open street map , or how know the srid code for one input (lat,lon) pnt = GEOSGeometry('POINT(-96.876369 29.905320)', srid=srid_from_lat_lon) thanks -
limiting the number of displayed instances of a model in Django Admin
I have a model which over timer will have several thousand to tens of thousands of instances. Each of those is unique. In the Django Admin interface I can see all the instances and access them ect. Is there a way for me to limit the number of instances I can see to lets say 20 or 50 sorted in whichever order and I can look through them like pages? I ask because loading all several thousand instances will likely clog up my server. So how do I limit it? My model is as follows if that helps: #Student Type class StudentType(models.Model): name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Name') def __unicode__(self): return self.name #Old -- Deprecated:Student Images Folder def student_directory_path(instance, filename): return 'students/%s' % filename #Student Images Folder def st_profile(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'students/%s' % filename #Student Profile class ProfileStudent(models.Model): user = models.OneToOneField(app_settings.USER_MODEL,) created = models.DateTimeField(auto_now=False, auto_now_add=True, blank = False, null = False, verbose_name = 'Creation Date') email = models.EmailField(max_length=254, blank=True, null=True) name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Name') last_name = models.CharField(max_length = 400, null=True, blank = True, verbose_name = 'Last Name') phone_number = β¦ -
Pass arguments to serializer DRF
Well I'm struggling at sending arguments to the serializer class, my code looks like: models.py class Transaction(models.Model): owner = models.ForeignKey(User, on_delete=models.SET("DELETED"), related_name='transactions') date = models.DateField(auto_now_add=True) concept = models.CharField(max_length=100) value = models.DecimalField(max_digits=10, decimal_places=2) total = models.DecimalField(max_digits=10, decimal_places=2) serializers.py class TransactionSerializer(serializers.ModelSerializer): total = serializers.ReadOnlyField(source='new_total') owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Transaction fields = '__all__' views.py class TransactionHandler(viewsets.ModelViewSet): queryset = Transaction.objects.all() serializer_class = TransactionSerializer def perform_create(self, serializer): last_transaction = Transaction.objects.latest('id') new_total = last_transaction.total + Decimal(self.request.data['value']) serializer.save(owner=self.request.user, new_total=new_total) When in the serializer.save() method there is only the owner argument all works fine but when I add the second argument all gets messy -
invalid literal for int() with base 10: 'choosen_room_1_id'
I was trying to access part of the model self attributes, however after migrations this error showed up. The model works perfectly fine before I ran makemigrations and migrate. After reading through the value error page, I notice that the value error was cause by the model trying to access it's own foreign key(choosen_room_1) under a property function. models.py def getTotalPricing(self): total_price = 0 amount = dict() if self.choosen_room_1 is not None: The choosen_room_1 attribute was defined as below: models.py choosen_room_1 = models.ForeignKey(ChoosenRoom, default=None, related_name="room_type_1", null=True) Some things I have tried so far are: remove old migrations file check if id field exist in the table using sqlite terminal, and it does exist force choosen_room_1 to_field as 'id' or 'choosenroom_id', same error still exist Using django admin interface I am sure the choosenroom wasn't null and was able to reassign it with a new foreign key item. Accessing choosen_room_1 using manage.py shell will give me the same error. After reading through some of the stackoverflow issues, my guess was somehow foreignkey was expecting the unique id key with integer type, however something went wrong during query process? As mention here btw, I was running this project under python2.7 with django β¦ -
Slow Image Loading with Lightbox Plugin and Amazon S3
I am hosting a Django app which displays images inside a gallery-view called lightbox (https://github.com/ashleydw/lightbox). Every Image is loaded via a presigned url from Amazon S3. The problem is that the image only starts loading as soon as it is viewed in the gallery, not any sooner. For some users this then takes a couple seconds to load. I am not to sure whether S3 is the bottleneck, but is there any method to force preloading of images that are currently "invisible"? Even preloading the next picture in the gallery would suffice I think. I am aware that Cloudfront enhances loading times from S3 as well, but is currently not an option. -
why is requirement.txt build failing in elastic beanstalk?
I am in the process of migrating a Django app from Heroku to Elastic Beanstalk. It is working fine in Heroku as is. I am getting the error Your requirements.txt is invalid. Snapshot your logs for details. When I dive into the eb-activity.log I see the failure seems to be related to atlas and scipy. I don't under why requirements.txt is invalid on aws but valid on heroku. Insight into what is causing this error and how to remedy would be greatly appreciated. My eb-activity.log /opt/python/run/venv/local/lib64/python3.4/site-packages/numpy/distutils/system_info.py:572: UserWarning: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. self.calc_info() /opt/python/run/venv/local/lib64/python3.4/site-packages/numpy/distutils/system_info.py:572: UserWarning: Lapack (http://www.netlib.org/lapack/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [lapack]) or by setting the LAPACK environment variable. self.calc_info() /opt/python/run/venv/local/lib64/python3.4/site-packages/numpy/distutils/system_info.py:572: UserWarning: Lapack (http://www.netlib.org/lapack/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [lapack_src]) or by setting the LAPACK_SRC environment variable. self.calc_info() Running from scipy source directory. Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-ix0qk_kf/scipy/setup.py", line 416, in <module> setup_package() File "/tmp/pip-build-ix0qk_kf/scipy/setup.py", β¦ -
How to used foreignkey data in extra field with inline in django
When we save foreign key object from django admin. As following screenshot click here to see the screenshot Newly created object will get saved but not been able to display at same time in dropdown list. We have measurement model which has material and product foreign key as showed in following snippet. So I want when object is created it should display the newly created option in foreign key dropdown. Please suggest how do I do that. Here is my code snippet models.py class MaterialName(models.Model): material_name = models.CharField(max_length=150, default=None, null=True, unique=True) class Product(models.Model): product_name = models.CharField(max_length=100) class Measurement(models.Model): product = models.ForeignKey(Product,default=None, null=True, related_name='Measurement') material_name = models.ForeignKey(MaterialName,default=None, blank=Blank, related_name='materialname') admin.py class MaterialTypeAdmin(admin.ModelAdmin): model = MaterialType list_display = ('material_type',) class ProductAdmin(admin.ModelAdmin): model = Product inlines = [MaterialTypeAdminInline,] -
Loaddata return error "Key (user_id)=(2) already exists."
i have data in Sqllite3, but i want to use PostgreSQL so i did dumpdata then loaddata it says this error: psycopg2.IntegrityError: duplicate key value violates unique constraint "uyelik_ders_bilgileri_uye_id_23796fd8_uniq" DETAIL: Key (user_id)=(2) already exists. i think it is about my models.py, because i created extended user profile with these codes: class ders_bilgileri(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) dersler = models.TextField(max_length=500,blank=True,default="bos") facebook_adresi=models.URLField(max_length=1000,blank=True) facebook_mesaj_gonderilsin=models.BooleanField(default=True) twitter_mention_atilsin=models.BooleanField(default=True) twitter_adresi = models.CharField(max_length=1000,blank=True) facebook_idsi=models.CharField(max_length=100,blank=True,default="yok") pushed_id=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.user) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: ders_bilgileri.objects.create(user=instance) I tried then get_or_create but nothing changes, what is the problem you think? -
Can I login in with Facebook as an unregistered user? (Django, all-auth)
I'm building my Django RESTful Framework to retrieve and post data for Mobile. I'm using djang-rest-auth (which is just all-auth with RESTful functionality; more info: http://django-rest-auth.readthedocs.io/en/latest/). Question: Social Auth in all-auth is not clear to me. Can you finish this use case? Use Case: Unregistered User User Login with Facebook on Mobile Mobile gets facebook token from Facebook SDK Mobile sends token to our DRF Backend server URL which is '/rest-auth/facebook' And what happens? Can you complete this Use Case? <- This is my question My guesses: all-auth automatically create new user for facebook user token and return new token? Then, it saves created user to settings.AUTH_USER_MODEL? Or...? I found 'social account' in Django admin. Are we saving User in this account..? -
how to setup django database accessed from 3 apps
I have 3 apps in a project. What I want to do are 2 things. (1) I want to setup each apps to access same database(Read & Write). I have no idea that I have to have same models.py each of my apps. If so, how can I migrate database. I tried it, but one app which was used to do migrate command success database access. But other 2 apps couldn't access database. And I tried to make simbolic link of models.py and migrations directory to each apps directories. But it didn't work too. (2) I want to use django authentication system to each of my apps. App1 (For Enduser) - (email, password) App2 (For Service provider) - (ID, password) App3 (For System Administrator) - (ID (different from App2), password) I can use django user authentication system from 1 app. But I want to make authentication system to 3 apps from different urls. App1 is a webview based app that use django via rest framework. App2 and App3 are web application (different url and port). Can I make it on using django? Would you give me some advice please? -
Django - creaing a custom model admin form field, passing the model instance to set a read only attribute
I know you can set readonly_fields in a model's admin.py but I am trying to make a field read only dependent upon it's (saved) value in the database. I can create a custom field Class, but am unable to pass the value of the model instance so I can achieve the above. Eg class MytypeField(models.CharField): def __init__(self,*args,**kwargs): PAGE_LAYOUT_CHOICES = ( ('column1','One Column'), ('column2','Two Columns') ) kwargs['max_length'] = 7 kwargs['choices'] = PAGE_LAYOUT_CHOICES kwargs['default'] = 'column1' super(MytypeField,self).__init__(*args,**kwargs) And in the model layout = MytypeField() Is there a way to do this in admin.py rather than in the model itself? I can't pass the model instance to this custom class, and I'm sure that's not the way to do it anyway! Many thanks! -
How to send customized response if the unauthroized credentials were provided in django rest
How to send customized response if the unauthroized credentials were provided in django rest class StockList(APIView): permission_classes = [IsAuthenticated] def get(self,request): stocks = Stock.objects.all() serializer = StockSerializer(stocks,many=True) return Response({'user': serializer.data,'post': serializer.data}) def post(self): pass Here when I Hit url by invalid credentials i get 401 error on deveploment server. But i want to send customized response on client using json. any suggestions are welcomed. Thank you.. -
Django Formsets with ModelBase Not rendering the Checkbox default but a drop down list instead
I need to create a required checkbox option if no_new_item exists. I am using the model.NullBoolean field, which, according to Django docs should render the checkbox widget. Instead I am getting a drop down list with 'Yes' and 'No.' How would I go about creating the checkbox in the Base model.Models? /models.py class StoreNightlyReport(models.Model): store_number = models.ForeignKey('Stores', verbose_name='Store Number', max_length=20, null=True) date = models.DateField(null=True) #managers = models.ManyToManyField('auth.User', blank=True, null=True) def __str__(self): return self.store_number.store_number class StoreNightlyReportsBase(models.Model): store_nightly_report = models.ForeignKey(StoreNightlyReport) no_new_item = models.NullBooleanField(verbose_name='No New Items', default=True) customer = models.CharField(verbose_name='Customer Name', max_length=20, null=True) class Meta: abstract = True /forms.py class StoreNightlyReportsForm(ModelForm): class Meta: model = StoreNightlyReport widgets = {'date': SelectDateWidget()} exclude = () def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(StoreNightlyReportsForm, self).__init__(*args, **kwargs) if 'store_number' in self.fields: if not user.is_superuser: self.fields['store_number'].queryset = Stores.objects.filter(managers=user) /views.py class StoresNightlyReportsNewLoansCreate(CreateView): template_name = 'reports/storenightlyreport_form.html' model = StoreNightlyReport form_class = forms.StoreNightlyReportsForm success_url = reverse_lazy('reports:storenightlyreports') def get_form(self, form_class=None): form_class = self.get_form_class() form = form_class(self.request.POST or None, user=self.request.user) self.formsets = {} StoreNightlyReportsNewLoanFormSet = inlineformset_factory(StoreNightlyReport, StoreNightlyReportsNewLoan, exclude=[], extra=1) self.formsets['new_loan'] = StoreNightlyReportsNewLoanFormSet(self.request.POST or None) def get_context_data(self, **kwargs): data = super(StoresNightlyReportsNewLoansCreate, self).get_context_data(**kwargs) data['formset_new_loan'] = self.formsets['new_loan'] return data def get_context_data(self, **kwargs): data = super(StoresNightlyReportsNewLoansCreate, self).get_context_data(**kwargs) #formset_renewal = StoreNightlyReportsRenewalFormSet() data['formset_new_loan'] = self.formsets['new_loan'] return super(StoresNightlyReportsNewLoansCreate, self).form_invalid(form) /template.html β¦ -
Removing reference to BaseClass in Django Migrations
I have the following models. class ReservedSlug(models.Model): slug = models.SlugField( max_length=80, unique=True, ) class SubClass(ReservedSlug): name = models.CharField( max_length=100, ) Now what happens in the database is that the SubClass has a foreign key relation to the ReservedSlug Base class of the following: CONSTRAINT reservedslug_ptr_id_f48f6b16_fk_utils_reservedslug_id FOREIGN KEY (reservedslug_ptr_id) REFERENCES public.utils_reservedslug (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED And at the same time, it is setting the primary key to the following: CONSTRAINT subclass_newsubclass_pkey PRIMARY KEY (reservedslug_ptr_id), My goal is to remove the reference to Reserved slug all together and just have reservedslug_ptr_id be an IntegerField in SubClass model. This is one of the ways I have tried inside the migrations: database_operations = [ migrations.AlterField( model_name="subclass", name="reservedslug_ptr_id", field = models.ForeignKey('reservedslug_ptr_id', db_constraint=False, db_index=True, null=False) ) ] state_operations = [ migrations.AlterField( model_name='subclass', name='reservedslug_ptr', field=models.IntegerField(db_index=True, null=False), ) ] operations = [ migrations.SeparateDatabaseAndState( database_operations=database_operations, state_operations=state_operations And no matter what I do, I cannot get it to the way I want to get it. I keep getting this error: django.core.exceptions.FieldError: Auto-generated field 'reservedslug_ptr' in class 'SubClass' for parent_link to base class 'ReservedSlug' clashes with declared field of the same name. I have been at this for the past 2 β¦ -
how to configure nginx to indicate β/β to my main page
i have a django project and my web static files are at 'web/' directory here is the structure: β web git:(ycw.alpha) tree -L 4 . βββ forward βββ asserts β βββ img β β βββ background β β βββ qr β β βββ thumb β βββ style β βββ css β βββ sass βββ index.html βββ package.json βββ script.js βββ source βββ unit i have configured Nginx conf and i want nginx to directly indicate to 'web/forward/index.html' when i request my own website 'http://example.com' i do the thing above like this: location / { index index.html root /path/to/my/django/project/; } location /index.html { alias /path/to/my/django/project/web/forward/index.html; } it indeed directly redirects to 'index.html', but the question is there are some references in 'index.html' to some static files such as img or css and the paths are relative paths like './asserts/style/css/index.css' so consequently these files are not found as 404 how can i configure it correctly? -
Expanding the list of relationship field arguments
Iβm looking for a way to expand the list of relationship field arguments, e.g. to add a predicate for each direction of the relation. My first guess was to define a subclass of models.ForeignKey class NewForeignKey(models.ForeignKey): def __init__(self, parent, pred='', reverse_pred='', **kwargs): self.pred = pred, self.reverse_pred = reverse_pred super(NewForeignKey, self).__init__(parent, **kwargs) Then use this subclass in my models as in the following example: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = NewForeignKey (Question, pred="refers to", reverse_pred="includes", on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) Initially, this seemed to work fine, however, when I tried to pass it through makemigrations it failed with the following error message: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 445, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\makemigrations.py", line 99, in handle ProjectState.from_apps(apps), File "C:\Python27\lib\site-packages\django\db\migrations\state.py", line 178, in from_apps model_state = ModelState.from_model(model) File "C:\Python27\lib\site-packages\django\db\migrations\state.py", line 354, in from_model e, TypeError: Couldn't reconstruct field question on polls.Choice: __init__() takes at least 2 arguments (1 given) Digging deeper, I couldnβt find an explanation why β¦