Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I deployed django project with nginx+uwsgi, there was always a 502 bad gateway error. What is the reason?
When I enter my IP in the browser, the page will appear 502 Bad Gateway. Is this my configuration file wrong? /etc/nginx/sites-enabled/fefault: server { listen 80; root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name 47.101.157.128; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. #try_files $uri $uri/ =404; include uwsgi_params; uwsgi_pass 47.101.157.128:8000; } location /static{ alias /var/www/sscc2019/static/; } /home/sscc/sscc2019/uwsgi.ini: [uwsgi] socket=47.101.157.128:8000 chdir=home/sscc/sscc2019 wsgi-file=sscc2019/wsgi.py processes=4 threads=2 master=True pidfile=uwsgi.pid daemonize=uswgi.log module=sscc2019.wsgi:application vacuum=true virtualenv=/home/ssccenv -
Creating a many models with a single submit
A'm beginner at Django. Sry for my bad english) There are 2 models: 1.RelationType; 2. RequestRelation. The second model is connected with the first through MTM field. There is a multiple select form based on a list of “relationship types”. Need to create few models of when RequestRelation submitting, depending on the selected items of the multi-select? F.e., if "husband / wife / son" is chosen, need to create 3 models accordingly. Distinctive in them are only the types of relationships. The form.is_valid(), the correct values come. But so far, only one model is created, with lists of all selected relationship types. Also in my code there is a bug. The model is created immediately when the page is loaded, not when it is submitted. Thank you in advance. models.py class RelationType(models.Model): title = models.CharField(max_length=40) def __unicode__(self): return self.title class RelationRequest(models.Model): creator = models.ForeignKey(User, related_name='creator') relation = models.ForeignKey(User, related_name='relation') type_of_relation = models.ManyToManyField(RelationType, related_name='type_relation', verbose_name=_('type_relation')) status = models.BooleanField(_('status'), default=False) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) html <form action="" method="POST" multiple="multiple"> {% csrf_token %} {{ relation_form.type_of_relation }} <input type='submit' value='ok'> </form> forms.py class RelationRequestForm(forms.ModelForm): class Meta: model = RelationRequest fields = ('type_of_relation',) widgets = { 'type_of_relation': forms.SelectMultiple( attrs={ 'class': 'select2', … -
django admin redirect I can't get a connection
django admin redirect I can't get a connection....... admin.py from django.contrib import admin from .models import * from django.utils.html import format_html from django.shortcuts import redirect class RecommendLaywerAdmin(admin.ModelAdmin): def sale(request): return redirect(request, "admin/sale_view.html", {}) admin.site.register(RecommendLaywer, RecommendLaywerAdmin) I can't get through......... The location of the file is as follows. C:\workspace\bhsn\admin.py The location of the html file is as follows: C:\workspace\bhsn\template\admin\sale_view.html How do I get the sales_view.html connected? -
How change unicode language of dumpdata in .json format
I created dumpdata but when i try to load this by using command: py manage.py loaddata backup.json Then i have error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Then when i opened this database by Notepad then it shown me that its encoded in UCS-2 LE BOM, how I can save dumpdata in UTF-8 language? -
Django Multiple File Upload With ModelForm
I am trying to upload multiple files through a model form. View.py def OrderCreate(request): if request.method == 'POST': #NEED TO HANDLE MULTIPLE FILES/FOLDER form = OrderForm(request.POST, request.FILES) if form.is_valid(): email = form.emailer() # SAVE FORM form.save() email.send() form = OrderForm() return redirect('Order-View', sorting = 0) else: form = OrderForm() return render(request, 'users/order_form.html', {'form':form}) Forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = [ 'order_status', 'order_appraiser', 'order_address', 'order_city', 'order_state', 'order_client', 'order_fee', 'order_due_date', 'order_files', 'order_notes'] widgets = { 'order_due_date': DateInput(), 'order_notes': TextInput(), 'order_files': AdminFileWidget(), } def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['order_status'].label = "Status" self.fields['order_appraiser'].label = "Appraiser" self.fields['order_address'].label = "Address" self.fields['order_city'].label = "City" self.fields['order_state'].label = "State" self.fields['order_client'].label = "Client" self.fields['order_fee'].label = "Fee" self.fields['order_due_date'].label = "Due Date" self.fields['order_notes'].label = "Notes" Template <div class="form-row mt-2"> <div class= "form-group col-md-4 dropzone"> {{form.order_files|as_crispy_field}} </div> </div> Right now it will handle a single file. I have been unable to find any solutions that handle this problem while using a model form and a template with crispy tags. It looks like your post is mostly code; please add some more details. Don't know what other details I could add so here is an article to override this error. -
Django cross apps foreign keys. What to worry about?
Morning guys, as title says, I have many apps with many foreign keys referencing other apps in a single Django project. FYI, 90% of these apps won't be reused. Since i am already half my way to complete the whole project, but I am wondering are there issues with such structures? Things that pop into my mind: migrations corrupt coz too many foreign keys across apps (read about it but not sure true or nay) maintenance gets confusing. Too many apps cause performance issue. (let's say 50 apps in one proj) i don't know, i need to seek your professional advice bruh. thanks with love with SO -
How to retrieve the field values from model objects
I have the following model which contains 2 List Field's: class Cimex_Search(models.Model): search_engine = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) web_technology = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) def __str__(self): return "default" Now I have the following function in views.py: def cimex_search_searcher(request): default_table = Cimex_Search.objects.get(id=1) field_type = request.GET.get('fieldtype') print(default_table.field_type) ###! NEED HELP HERE How to pass the fieldtype value to the Model Object? I Would like to retrieve the model object list based on the fieldtype input parameter value. What is the best way to tackle this problem? -
How can I override a DjangoModelFormMutation field type in graphene?
I'm building a simple recipe storage application that uses the Graphene package for GraphQL. I've been able to use Django Forms so far very easily in my mutations, however one of my models fields is really an Enum and I'd like to expose it in Graphene/GraphQL as such. My enum: class Unit(Enum): # Volume TEASPOON = "teaspoon" TABLESPOON = "tablespoon" FLUID_OUNCE = "fl oz" CUP = "cup" US_PINT = "us pint" IMPERIAL_PINT = "imperial pint" US_QUART = "us quart" IMPERIAL_QUART = "imperial quart" US_GALLON = "us gallon" IMPERIAL_GALLON = "imperial gallon" MILLILITER = "milliliter" LITER = "liter" # Mass and Weight POUND = "pound" OUNCE = "ounce" MILLIGRAM = "milligram" GRAM = "gram" KILOGRAM = "kilogram" My Model: class RecipeIngredient(TimeStampedModel): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients') direction = models.ForeignKey(RecipeDirection, on_delete=models.CASCADE, null=True, related_name='ingredients') quantity = models.DecimalField(decimal_places=2, max_digits=10) unit = models.TextField(choices=Unit.as_tuple_list()) My form: class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient fields = ( 'recipe', 'direction', 'quantity', 'unit', ) My Mutation: class CreateRecipeIngredientMutation(DjangoModelFormMutation): class Meta: form_class = RecipeIngredientForm exclude_fields = ('id',) I've created this graphene enum UnitEnum = Enum.from_enum(Unit) however I haven't been able to get graphene to pick it up. I've tried adding it to the CreateRecipeIngredientMutation as a regular field like unit … -
Django's best way to load data into postresql database
I’m working in a project that consists in converting a local postgresql database (that uses sqlalchemy as the ORM) into a web application, in which I upload excel sheets, read them, do some small cleaning and then upload selected data into a postgresql database using Django’s ORM. The idea is to have the data in a server instead of in every user’s machine. Everything is ok but data loading is taking too long since, I think, I am using panda’s dataframes to easily structure, read and save the data. In the local version of the library, I used lists and was way faster. I don’t if it’s related to Sqlalchemy, Django, lists or dataframes. Any suggestions on how to read spreadsheets data and upload it into a postgresql database using Django? Thanks a lot. -
How to dynamically add React componsents from websockets
I've been working through a couple of tutorials on integrating Django and React, and making some modifications to learn the platform better. So far, when the page loads, React queries Django REST api and, based on that input, loads a number of City components. The code looks like this: class CityList extends React.Component { constructor(props) { super(props); this.state = { cities: [], newCities: [] }; } componentDidMount() { axios.get("http://127.0.0.1:8000/api/").then(res => { this.setState({ cities: res.data }); document.body.style.background = "#131C2F"; }); } render() { console.log(this.state.articles); return ( <div className="row" id="mainRow" style={{ backgroud: "#304877" }}> <div className="col-lg-9 col-sm-10" style={{ backgroud: "#304877" }}> <ul className="mainList"> {this.state.cities.map(city => { return <Cities city={city} />; })} </ul> </div> <div className="col-lg-3 col-sm-2" style={{ backgroud: "#304877" }}> <div className="form-signin search-box" style={{ position: "fixed" }}> <h1 className="h3 mb-3 font-weight-normal" style={{ textAlign: "center", fontSize: "22px", color: "white" }} > Add location </h1> <br /> <input type="text" name="location" id="myLocation" className="form-control" placeholder="City" /> <br /> <div className="btn btn-primary btn-block" onClick={this.handleClick} > Add </div> </div> </div> </div> ); } } I've tried adding a web socket which would push new City components from Django backend. The socket is created by: var mySocket = new WebSocket('url to backend'); This also works fine, and receives objects … -
Shell saying that django_cleanup module I've installed don't exist
Like in title I've installed django_cleanup by using: pip install django-cleanup and put in INSTALLED_APPS: INSTALLED_APPS = [ 'django_cleanup', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'shop', 'account', 'rest_framework', ] but now when I'm trying to run test or server in shell then i get: ModuleNotFoundError: No module named 'django_cleanup' -
Django filter queryset using a list
I have one table, table A that holds primary keys of all the objects in the table b, if I store all the primary keys from table A in a list, then is it possible to get a list of all the objects in table B using the primary keys I have stored in a list. like tableB.objects.filter(pks = list) is there any way I can construct a query set like the above that would get me a list of all the object with the primary keys. Please let me know. Thanks Shaham k -
Error while writing nested relationships in Django Rest Framework using drf_writable_nested
I'm currently trying to use the drf_writable_nested to perform updates and creates of my current db schema and I've been facing this error: The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer trvl.serializers.StatisticsSerializer, or set read_only=True on nested serializer fields. Main model: class Statistics(models.Model): """Instance: {airport_code, carrier_code, month, year, flight, delay_count, delay_time}""" airport = models.ForeignKey(Airport, on_delete=models.CASCADE) carrier = models.ForeignKey(Carrier, on_delete=models.CASCADE) month = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(12)]) year = models.IntegerField(validators=[MinValueValidator( 1900, message='Invalid year: year < 1900.')]) # statistics linkage flight = models.ForeignKey( FlightStatistics, on_delete=models.DO_NOTHING) delay_count = models.ForeignKey( DelayCountStatistics, on_delete=models.DO_NOTHING) delay_time = models.ForeignKey( DelayTimeStatistics, on_delete=models.DO_NOTHING) # Guaranteeing the "primary key" of the tuple class Meta: unique_together = ('airport', 'carrier', 'month', 'year') def __str__(self): return '%s_%s_%s_%s' % (self.airport, self.carrier, self.month, self.year) Serializer: class StatisticsSerializer(WritableNestedModelSerializer): # Using nest serializer for handling get and post # Using serializers instead of the model fields flight = FlightStatisticsSerializer() delaycount = DelayCountStatisticsSerializer() delaytime = DelayTimeStatisticsSerializer() class Meta: model = models.Statistics fields = ('airport', 'carrier', 'month', 'year', 'flight', 'delaytime', 'delaycount') View: class StatisticsView(viewsets.ModelViewSet): queryset = models.Statistics.objects.all() serializer_class = serializers.StatisticsSerializer -
Send data to users base on database event in Django channels
I have an application in Django that some users can add and update data. these users add or update data with Django standard forms and views. I want to implement an other app that send new data to all users when a user update or create data in database. i read about Django-channels that can handle web socket, but i can't find something about server or database events in Django-channels. So how can i send data to users when a database event occur? -
Update ModelForm without reload page on Django
views.py def KuryeAta(request): if(request.method=='POST'): barkod = request.POST['barkod'] form = Urun.objects.get(barkod=barkod) context = { 'form':form, } return render(request,'kurye-c2.html',context) def KuryeÇıkış(request): return render(request,'kurye-c.html') models.py class Urun(models.Model): barkod = models.CharField(verbose_name='Barkod',max_length=21) tarih = models.DateField(verbose_name='Tarih') teslimt = models.DateTimeField(verbose_name='Teslim Tarihi',default=timezone.now, blank=True) durum = models.CharField(choices=DURUMLAR, verbose_name='Durum',max_length=15,blank=True,default='Yola Çıkmadı') bkod = models.CharField(choices=KODLARIM, max_length=12,verbose_name='Bölge Kodu') alici = models.CharField(verbose_name='Alıcı',max_length=50) yakinlik = models.CharField(choices=DERECEM, verbose_name='Yakınlık',max_length=10,default='Kendisi') kurye = models.ForeignKey(Kurye, on_delete=models.CASCADE, verbose_name='Kurye', related_name='zimmet',blank=True,null=True) def __str__(self): return u'Barkod:[%s] Alıcı: %s / Kurye: %s' % (self.barkod,self.alici,self.kurye) template.html <form action="{% url 'kuryea' %}" method="post"> {% csrf_token %} </div> {{ veri.non_field_errors }} <div class="col-sm-3 col-sm-6 col-lg-6"> <label>Barkod No:</label><br/> <input type="text" name="barkod"> </br><br/> </div> <div class="col-sm-3 col-sm-6 col-lg-6"> <div class="form-actions form-group"><button id="atama" type="submit" class="btn btn-success btn-sm">Gönder</button></div> </div> </form> and here's my forms.py class UrunEkle(forms.ModelForm): class Meta: model = Urun fields = [ 'barkod', 'tarih', 'teslimt', 'durum', 'bkod', 'alici', 'yakinlik', 'kurye', ] widgets = { 'tarih':forms.TextInput(attrs={'type':'date'}), 'teslimt':forms.TextInput(attrs={'type':'date'}), } Now for example, I'd like to update only the 'kurye' of this instance and save it. How can I do that ? without reload page. This app for courier management system but i can not get data and update 'kurye' value because system wants full of fields of 'UrunEkle' form. So im newbie on python, thanks for helps. -
python manage.py makemigrations
error messages I received when trying to install the project "https://github.com/practical-recommender-systems/moviegeek" on my suggestion systems. using python 3.7 and django 2.1.7 python manage.py makemigrations error message error message -
Turn off input history for Django admin model charfields
I am working on a website built with Django and am wondering if there is a way to turn off the input history for charfields when editing a database as administrator. I have found ways to do this for forms, but not directly editing the database as an administrator. For example: class Material(models.Model): name = models.CharField(max_length=100, help_text='Enter the material name', autocomplete='off') latex_name = models.CharField(max_length=100, help_text='Enter the latex encoded material name', blank=True) category = models.CharField(max_length=1, choices=(('o','Organic'), ('i','Inorganic')), help_text='', blank=True) comments = models.CharField(max_length=1000, blank=True) def __str__(self): return(self.name) When I log on to the website as administrator and add a new material instance, the character fields all have drop down menus of the past strings I've inputted. How can I disable this? -
django manytomanyfield filter
so I am building an app with django django rest and I have some issues with many to many fields in my models, in the app there are two models that are connected by a many to many field option and version. the problem is that I want to filter my option and get only the option related to a number of version and only those who have (Default True). here is my models class Option(models.Model): Code_Option = models.CharField(max_length=20, primary_key=True) Nom_Option = models.CharField(max_length=100) option_Version = models.ManyToManyField(Version,through='Option_Version') class Option_Version(models.Model): option = models.ForeignKey(Option, on_delete=models.CASCADE) version = models.ForeignKey(Version, on_delete=models.CASCADE) Default = models.BooleanField(default = False) class Version(models.Model): Code_Version = models.CharField(max_length=20, primary_key=True) Nom_Version = models.CharField(max_length=200) Id_Modele = models.ForeignKey(Modele, on_delete=models.CASCADE, related_name='Version_set') and here is what I tried to do class Option_defaut_Version(ListAPIView): serializer_class = Option_Version_Sereializer def get_queryset(self): id_version = self.kwargs['Id_Version'] return Option.objects.filter(option_Version__version = id_version).filter(option_Version__default = "True") if anyone could help me I would apreciate it ps: I saw a lot of other questions and answers also the doc from django django rest but it didn't help me -
Django JQuery Ajax events not triggered
i extended my django-admin detail site with some javascript magic..., before an ajax requests gets sent, i want to manipulate it with global ajax beforeSend handler, my setup: {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} <script> django.jQuery(document).ready(function() { console.log('a') django.jQuery.ajaxSetup({ beforeSend: function(xhr, settings) { console.log('b') } }) }) </script> {% endblock %} What happens: Console prints a but it doesnt print b Can anybody explain it to me or help me out? I read almost every documentation, but there is no hint why my beforeSend is not executed. Greetings and thanks ! -
error: command 'gcc' failed with exit status 1 django install mysqlclient
im trying to install mysqlclient for my django =2.1 project on my terminal cpanel but i get this error python =3.6 Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command /home/zettapcc/virtualenv/zetta/3.6/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-fgxxo9e_/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-bz9c5kx6/install-record.txt --single-version-externally-managed --compile --install-headers /home/zettapcc/virtualenv/zetta/3.6/include/site/python3.6/mysqlclient: /opt/alt/python36/lib64/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/MySQLdb gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,4,2,'post',1) -D__version__=1.4.2.post1 -I/usr/include/mysql -I/usr/include/mysql/.. -I/opt/alt/python36/include/python3.6m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o unable to execute 'gcc': Permission denied error: command 'gcc' failed with exit status 1 i also … -
Django: Accessing Non-Unique Fields
I apologize. I am also surprised I can't find this question asked already. Embarrassment in 3, 2, 1... How do I access another model's non-unique field? Let us say we have 2 people and a pet, simplified to instantiated JSON examples: Person 1: { id: 1, first_name: "John", last_name: "Doe" } Person 2: { id: 2, first_name: "Jane" last_name: "Doe" } Pet: { id: 1, name: "Guess", owner_first_name: "{I want person 1's, first_name string value here}", owner_last_name: "{I want person 1's, last_name string value here}" } I get that an object requires a unique primary key, most frequently "id", but there's got to be a way to access secondary fields after using a functional PK. I know the models.to_field would currently work to access first name, if it's set to unique=True. Eventually, there will be another "John" or "Jane", and there's already 2 "Doe"s here. Forgive the syntax butchery for simplification, but how do I get this in Django? Pet.owner_first_name = Person[id].first_name(unique=False) -
Two Factor in Django?
I'm trying to add Two Factor authentication in django. I made some research but i found very little. I only found this library but the docs are not really friendly for someone who's starting with Django, and the example did not clarify it. Is there an already existing open source example that i can study? Where i can see how 2fa is integrated, how does it behave with a login view etc. ? Thanks in advance. -
Django try except error for 'AnonymousUser'
I'm just a student. I have this kind of code. I use the Try except condition for the user_membership. But i wonder how can i solve the 'AnonymousUser' object is not iterable error if the user is not login.. i tried to hide the disabled button by using user.is_authenticated but it's not working. views.py def BookDetail(request, id): most_recent = Book.objects.order_by('-timestamp')[:3] book= get_object_or_404(Book, id=id) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = book form.save() return redirect(reverse("book-detail", kwargs={ 'id': book.pk })) try: user_membership = Customer.objects.get(user=request.user) except Customer.DoesNotExist: user_membership = None context = { 'user_membership': user_membership, 'form': form, 'book': book, 'most_recent': most_recent, } return render(request, 'catalog/book_detail.html', context) and my book_detail.html {% if user_membership and user_membership.user == request.user %} {% for content in book.pages %} <a href="{{ content.get_absolute_url }}" class="site-btn">Read</a> {% endfor %} {% else %} <button class="site-btn" disabled="disabled">VIP</button> {% endif %} -
Calling Model.refresh_from_db() not working after saving model with ForeignKey assignment
I'm writing some tests for a quiz/test application for Django. The relevant model is PreguntasPrueba, which is an appearance of a question in a quiz, and holds ForeignKey relations with the Quiz (Diagnostico) model, the Answer (Respuesta) model (This is the user's response), and the Question (Pregunta) model. relevant fragment of models.py: class PreguntasPrueba(models.Model): prueba = models.ForeignKey( "Diagnostico", on_delete=models.CASCADE, editable=False, related_name='preguntas_usadas' ) pregunta = models.ForeignKey( "Pregunta", on_delete=models.CASCADE, related_name='apariciones' ) respuesta = models.ForeignKey( "Respuesta", on_delete=models.CASCADE, null=True, related_name='seleccion_usuarios' ) In test.py, I create in setUpTestData a bunch of Pregunta instances (each with a set of Respuesta instances associated and then create a Diagnostico instance. In one of the test, I try to assert that my method for validating correct answers is working, by assigning an answer instance to the question appearance instance (refer above model), but when doing so, I call save() and refresh_from_db() on the instance, and the ForeignKey assignment does not work. I'm completely lost as to why this happens... Any help would be appreciated. relevant fragment of test.py: # get all the questions used in the quiz instance (I'm certain there are only 3) preguntas = self.diagnostico.preguntas_usadas.all() # assign individually corresponding Respuesta (answer) instances (This is kinda simulating a … -
Can you help me solve this when deploy my page?
Python - Django framework Hello people, I have a problem kills my head, I followed all the steps, and when I try to deploy my page to Heroku, I get the following error: remote: ! Requested runtime (Python-3.7.2) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app.